虽然需要做更多的工作才能开始,但我更喜欢使用 XPath,它是查询 XML 的更强大的方式......
在更新 XML 示例以便可以阅读之后...
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<books>
<book id="1">
<title name="Everyday Italian" category="cooking" year="2005" price="30.00"/>
<author name ="Giada De Laurentiis"/>
</book>
<book id="2">
<title name="XQuery Kick Start" category="web" year="2003" price="49.99"/>
<author name ="James McGovern"/>
<author name ="Per Bothner"/>
<author name ="Kurt Cagle"/>
<author name ="James Linn"/>
</book>
</books>
</bookstore>
我用这个...
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class TestXPath100 {
public static void main(String[] args) {
InputStream is = null;
try {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("Test.xml"));
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
XPathExpression exp = xPath.compile("//author");
NodeList nl = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
System.out.println(nl.getLength());
} catch (ParserConfigurationException | XPathExpressionException | SAXException | IOException ex) {
} finally {
try {
is.close();
} catch (Exception e) {
}
}
}
}
哪个输出5
。
基本上,xPath 查询会查找文档中任何被命名的节点author
查看XPath 教程以获取更多详细信息
更新了其他示例
如果您花时间阅读XPath 教程,您就会知道 XPath 是一种用于 XML 的查询语言(有点像 SQL 是一种用于数据库的查询语言)...
所以我更改了代码以转储name
所有匹配元素的属性并使用查询//book[title[@name='Everyday Italian']]/author
XPathExpression exp = xPath.compile("//book[title[@name='Everyday Italian']]/author");
NodeList nl = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
for (int index = 0; index < nl.getLength(); index++) {
Node node = nl.item(index);
System.out.println(node.getAttributes().getNamedItem("name"));
}
它输出...
name="Giada De Laurentiis"
我将查询更改为//book[title[@name='XQuery Kick Start']]/author
并输出...
name="James McGovern"
name="Per Bothner"
name="Kurt Cagle"
name="James Linn"