【问题标题】:Applying xpath on xml with default namespace with XOM使用 XOM 在具有默认命名空间的 xml 上应用 xpath
【发布时间】:2012-12-29 11:36:42
【问题描述】:

我在下面有一个包含默认命名空间的 XML

<?xml version="1.0"?>
<catalog xmlns="http://www.edankert.com/examples/">
  <cd>
    <artist>Stoat</artist>
    <title>Future come and get me</title>
  </cd>
  <cd>
    <artist>Sufjan Stevens</artist>
    <title>Illinois</title>
  </cd>
  <cd>
    <artist>The White Stripes</artist>
    <title>Get behind me satan</title>
  </cd>
</catalog>

我正在运行以下代码,期望得到一些结果

Element rootElem = new Builder().build(xml).getRootElement();
xc = XPathContext.makeNamespaceContext(rootElem);
xc.addNamespace("", "http://www.edankert.com/examples/");   
Nodes matchedNodes = rootElem.query("cd/artist", xc);
System.out.println(matchedNodes.size());

但大小始终为 0。

我经历过

期待任何帮助。

【问题讨论】:

标签: java xpath xml-namespaces xom


【解决方案1】:

XPath 中无前缀的名称总是意味着“没有命名空间”——它们不尊重默认的命名空间声明。您需要使用前缀

Element rootElem = new Builder().build(xml).getRootElement();
xc = XPathContext.makeNamespaceContext(rootElem);
xc.addNamespace("ex", "http://www.edankert.com/examples/");   
Nodes matchedNodes = rootElem.query("ex:cd/ex:artist", xc);
System.out.println(matchedNodes.size());

XPath 表达式使用原始文档未使用的前缀无关紧要,只要绑定到 XPath 命名空间上下文中前缀的命名空间 URI 与绑定的 URI 相同xmlns 在文档中。

【讨论】:

  • 只是另一个提示,您必须添加 xpath 表达式中使用的所有标签的所有命名空间,而不仅仅是合格的标签。就我而言,问题在于它缺少我的非限定名称空间的 addNamespace :(
猜你喜欢
  • 2013-02-02
  • 2011-04-25
  • 2011-10-09
  • 1970-01-01
  • 2010-10-09
  • 2013-06-23
相关资源
最近更新 更多