的包文档javax.xml.xpath
给出了很好的介绍,但这里也有一些示例代码:
InputSource xml = new InputSource(new StringReader("<a>\n" +
"<b>\n" +
"<c id=\"00001\" time=\"1:00\" day=\"Friday\" name1=\"John\" name2=\"Mary\"></c>\n" +
"<c id=\"00002\" time=\"2:00\" day=\"Monday\" name1=\"Ed\" name2=\"Kate\"></c>\n" +
"<c id=\"00003\" time=\"3:00\" day=\"Sunday\" name1=\"Mary\" name2=\"Ed\"></c>\n" +
"<c id=\"00004\" time=\"4:00\" day=\"Friday\" name1=\"Kate\" name2=\"John\"></c>\n" +
"</b>\n" +
"</a>"));
所以没有 SAX,但任何 DOMInputSource
都可以。之后是:
String name = "John";
XPath xpath = XPathFactory.newInstance().newXPath();
// the String.format is just here so you can see the XPath expression more
// clearly without all the ".."+x+".." string concat, feel free to replace
String expr = String.format("//a/b/c[@name1='%s']", name);
Node c = (Node) xpath.evaluate(expr, xml, XPathConstants.NODE);
NamedNodeMap attribs = c.getAttributes();
String id = attribs.getNamedItem("id").getNodeValue();
String time = attribs.getNamedItem("time").getNodeValue();
// etc.
如果元素名称c
在整个文档中是唯一的,则可以将 XPath 表达式缩减为//c[@name1='%s']
.
如果您需要同时匹配两者name1
并name2
使用此节点测试:[@name1='%s' or @name2='%s']
. 在这种情况下,您可能还需要获取NodeList
fromevaluate()
来处理多个匹配项:
NodeList c = (NodeList) xpath.evaluate(expr, xml, XPathConstants.NODESET);