【问题标题】:XPath query not returning elements after declaring schema [duplicate]XPath 查询在声明架构后不返回元素 [重复]
【发布时间】: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 默认命名空间”找到其他人。

标签: java xml xpath xsd


【解决方案1】:

在 XPath 1 中,note 之类的步骤在 no 命名空间中选择名为 note 的元素,您已将元素放入命名空间,因此您的路径具有“不合格”名称(即没有前缀) 不选择任何输入元素。您的 Java 代码需要绑定一个前缀(例如 w3s 到命名空间 URI(即 https://www.w3schools.com),然后将该前缀与例如 w3s:note 一起使用。

或者使用 XPath 2 或 3 或 XQuery 实现,您可以在其中为路径表达式声明默认元素名称空间,以便您的步骤 note 将选择您设置的默认元素名称空间中的元素,例如https://www.w3schools.com.

如果您想忽略 XPath 评估的命名空间,由于 XPath 1 的前缀麻烦,您可能会明确地不使用命名空间感知文档构建器,而是使用不感知命名空间的文档构建器。

对于 XPath 2 或更高版本或 XQuery 1 或更高版本,您还可以使用命名空间通配符,例如 *:note。

【讨论】:

    猜你喜欢
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 2015-02-07
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多