【发布时间】:2021-11-15 01:19:29
【问题描述】:
我尝试在 Java 中使用 XPath 从 XML 中获取元素。
如果没有架构定义/声明,一切都会按预期正常工作:
来自https://www.w3schools.com/xml/schema_howto.asp的示例
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XPath : /note/heading 返回一个元素
声明一个 xml Schema 后:
<?xml version="1.0"?>
<note
xmlns="https://www.w3schools.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.w3schools.com/xml note.xsd">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XPath /note/heading 不再工作了!!
Java 示例来自XPathTutorial
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("inventory.xml");
//Create XPath
XPathFactory xpathfactory = XPathFactory.newInstance();
XPath xpath = xpathfactory.newXPath();
System.out.println("n//1) Get book titles written after 2001");
XPathExpression expr = xpath.compile("/note/heading/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());
}
【问题讨论】:
-
这么多人掉进了这个陷阱!我选择了数百个示例中的一个作为副本;您可以通过搜索“XPath 默认命名空间”找到其他人。