xpath中的java搜索
假设这是xml:
<lib>
<books type="paperback" name="A" />
<books type="pdf" name="B" />
<books type="hardbound" name="A" />
</lib>
搜索type=“平装本”和name=“A”书籍的xpath代码是什么?蒂娅
目前我的代码如下所示:
import org.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.io.IOException;
import org.xml.sax.SAXException;
public class demo {
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("xml.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
// XPath Query for showing all nodes value
String version="fl1.0";
XPathExpression expr = xpath.compile("//books/type[@input="paperback"]/text()");
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());
}
}
}
# 1 楼答案
上面的答案很好。。。我想贡献一点资源。我看过的最好的xpath教程是here
# 2 楼答案
看一看here如果你正在努力学习xpath语法,它有几个很好的例子
此外,如果您只是需要XML和相关技术方面的帮助,请参阅指南here
# 3 楼答案
现在你似乎在寻找类似
<book><type input="paperback"/></book>
的东西,这显然是错误的。xpath表达式应该类似于//books[@type=“平装本”和@name=“A”]/text()