---
title: "java解析XML文件"
author: "willwen"
date: "2013-11-22T10:15:33Z"
tags: []
categories: ["编程语言"]
slug: "java-xml"
draft: false
lastmod: "2013-11-22T10:15:33Z"
id: 1979276
url: "https://willwen.iteye.com/blog/1979276"
---

解析报文：

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;root&gt;

&lt;fieldmap&gt;

&lt;field name="response\_um" type="10"/&gt;

&lt;field name="response\_code" type="3"/&gt;

&lt;/fieldmap&gt;

&lt;datas&gt;

&lt;row col1="MAJIAN034" col2="1"/&gt;

&lt;/datas&gt;

&lt;callresult errormessage=""/&gt;

&lt;/root&gt;

 

直接上代码：

```

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XmlParse {
	
	private static String getValue(Element pNode, String tagName) {
		NodeList nl = pNode.getElementsByTagName(tagName);
		if (nl.getLength() > 0) {
			return getInnerText(nl.item(0));
		}
		return null;
	}

	private static String getInnerText(Node pNode) {

		StringBuffer sb = new StringBuffer();
		Node n1 = pNode.getAttributes().getNamedItem("col1");
		Node n2 = pNode.getAttributes().getNamedItem("col2");
		System.out.println("UM: "+n1.getNodeValue());
		System.out.println("CODE: "+n2.getNodeValue());
		for (int i = 0; i < pNode.getChildNodes().getLength(); i++) {
			Node node = pNode.getChildNodes().item(i);
			if (node.getNodeType() == Node.TEXT_NODE) {
				sb.append(node.getNodeValue());
			}
		}
		return sb.toString();
	}
	
	public static void main(String[] args) throws Exception {
		//解析xml串
		String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><fieldmap><field name=\"response_um\" type=\"10\"/><field name=\"response_code\" type=\"3\"/></fieldmap><datas><row col1=\"MAJIAN034\" col2=\"1\"/></datas><callresult errormessage=\"\"/></root>";
		ByteArrayInputStream is = new ByteArrayInputStream(content
				.getBytes("UTF-8"));
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(is);
		Element root = doc.getDocumentElement();
		getValue(root, "row");
	}
}
```

 

运行结果：

UM: MAJIAN034

CODE: 1