XPath如何定位dom节点

XPath之于XML就好比SQL语言之于数据库。
XPath使用路径表达式来选取XML文档中指定的节点或者节点的结合。
表达式 义
 nodename 选取指定节点的所有子节点
/ 从根节点选取指定节点
// 根据指定的表达式,在整个文档中选取匹配的节点,这里并不会考虑匹配节点在文档中的位置。
. 选取当前节点
.. 选取当前节点的父节点
@ 选取属性
* 匹配任何元素节点
@* 匹配任何属性的节点
node() 匹配任何类型的节点
text() 匹配文本节点
| 选取若干个路径
[] 指定某个条件,用户查找某个特定节点或包含某个指定值的节点。

下面为dom解析中,XPath的运用:

准备一个xml文档:inventory.xml

<intentory>

<book year="2000">
<title>Show Crash</title>
<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>05553389858</isbn>
<price>14.95</price>
</book>

<book year="2005">
<title>Show Crash</title>
<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>05553389858</isbn>
<price>14.95</price>
</book>


<book year="1995">
<title>Show Crash</title>
<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>05553389858</isbn>
<price>14.95</price>
</book>
</intentory>

示列:

public static void main(String[] args) throws Exception {
//通过DocumentBuilderFactory静态方法创建 DocumentBuilderFactory
DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
//开启验证
documentBuilderFactory.setValidating(true);
documentBuilderFactory.setIgnoringComments(false);
documentBuilderFactory.setNamespaceAware(false);
documentBuilderFactory.setIgnoringElementContentWhitespace(false);

//创建DocuemntBuilder
DocumentBuilder builder=documentBuilderFactory.newDocumentBuilder();

builder.setErrorHandler(new ErrorHandler() {

@Override
public void warning(SAXParseException exception) throws SAXException {
System.out.println("warning:"+exception.getMessage());
}

@Override
public void fatalError(SAXParseException exception) throws SAXException {
System.out.println("fatalError:"+exception.getMessage());
}

@Override
public void error(SAXParseException exception) throws SAXException {
System.out.println("error:"+exception.getMessage());
}
});
//将文档加载到一个Docuement对象中
Document doc=builder.parse("src/com/newtouch/xml/inventory.xml");
//创建XPathFactory
XPathFactory factory=XPathFactory.newInstance();
//创建XPath对象
XPath xpath=factory.newXPath();
//创建XPath表达式
XPathExpression expr=xpath.compile("//book[author='Neal Stephenson']/title/.");
//通过XPath表达式得到结果,第一个参数指定了XPath表达式进行查询的上下文节点,也就是指定节点下查找符合XPath的节点。本列中的上下文节点是整个
//文档;第二个参数指定了XPath表达式的返回类型
Object result=expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes=(NodeList)result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}

}

猜你喜欢

转载自www.cnblogs.com/caibixiang123/p/9124495.html