您的位置:首页 > 其它

解析xml

2017-11-30 15:36 120 查看
package com.laiwei.lwiot.controller.bean;

import org.junit.Test;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.File;

/**
* Created by lw-yf-020 on 2017/3/10.
*/
public class XPathTest {
@Test
public void test() throws Exception{
// 解析文件,生成document对象
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(new File("C:\\Users\\lw-yf-020\\Desktop\\test.xml"));
// 生成XPath对象
XPath xpath = XPathFactory.newInstance().newXPath();

String expression = "/jetData/site/client/*";
//type下节点
NodeList nodeList = (NodeList) xpath.compile(expression).evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node nNode = nodeList.item(i);
Element element=(Element) nNode;
System.out.println(nNode.getNodeName()+":"+element.getAttribute("dataType"));
NodeList nodeList1=   element.getElementsByTagName("point");
//type下的元素
for (int j=0;j<nodeList1.getLength();j++){
Node node=  nodeList1.item(j);
Element element1=(Element) node;
System.out.println("pointId:"+element1.getAttribute("pointId")+"\t"+"pointName:"+element1.getAttribute("pointName")+"\t"+"context:"+element1.getTextContent());
}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: