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());
}
}
}
}
解析xml
最新推荐文章于 2024-04-15 15:35:05 发布