`
willwen
  • 浏览: 24637 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

java解析XML文件

    博客分类:
  • java
 
阅读更多

解析报文:

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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics