XPath 是一门在 XML文档中查找信息的语言。XPath可用来在 XML文档中对元素和属性进行遍历。XPath 是 W3C XSLT 标准的主要元素,并且 XQuery 和 XPointer 都构建于 XPath 表达之上。因此,对 XPath 的理解是很多高级 XML应用的基础。本文主要提供Xpath解析XML实例代码。
Java Xpath如何解析XML代码的代码如下:
/**
* @from www.ityuan.com
* @Description:Java Xpath如何解析XML代码详解
*/
public class XmlParseByXpathTester {
public void parserXML(String strXML) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
StringReader sr = new StringReader(strXML);
InputSource is = new InputSource(sr);
Document doc = builder.parse(is);
XPathFactory xFactory = XPathFactory.newInstance();
XPath xpath = xFactory.newXPath();
XPathExpression expr = xpath.compile("/root/student");
NodeList students = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i
Node type = students.item(i);
Element element = (Element) type;
System.out.println("student节点的属性值,id:" + element.getAttribute("id") + ",group:" + element.getAttribute("group"));
// 通过正则表达式,找出student节点的所有子节点
XPathExpression childNodeExpr = xpath.compile("./*");
NodeList list = (NodeList) childNodeExpr.evaluate(type, XPathConstants.NODESET);
for (int j = 0; j
Element emt = (Element) list.item(j);
System.out.println(emt.getNodeName() + "=" + emt.getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String inputXML =
"\n" +
"\n" +
"\n" +
"张三\n" +
"男\n" +
"18\n" +
"1990-09-09\n" +
"\n" +
"\n" +
"李四\n" +
"女\n" +
"17\n" +
"1990-10-10\n" +
"\n" +
"";
new XmlParseByXpathTester().parserXML(inputXML);
}
}
解析XML执行结果如下:
student节点的属性值,id:1,group:1
name=张三
sex=男
age=18
birthday=1990-09-09
student节点的属性值,id:2,group:2
name=李四
sex=女
age=17
birthday=1990-10-10