java解析XML文件

解析报文:

<?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>

 

直接上代码:


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

 

你可能感兴趣的:(解析xml)