使用XOM在具有默认名称空间的xml上应用xpath [英] Applying xpath on xml with default namespace with XOM

查看:115
本文介绍了使用XOM在具有默认名称空间的xml上应用xpath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have below XML which contains a default namespace

<?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>

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

And Im running following code expecting some result in return

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.

我经历了

  • https://stackoverflow.com/a/9674145/1160106 [I really didnt get the weired xpath syntax]
  • http://www.edankert.com/defaultnamespaces.html#Jaxen_and_XOM [Can see some hope. Just requires a major change in my current implementation]

期待任何帮助.

推荐答案

XPath中无前缀的名称始终表示无名称空间"-它们不遵守默认的名称空间声明.您需要使用前缀

Unprefixed names in XPath always mean "no namespace" - they don't respect the default namespace declaration. You need to use a prefix

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与通过xmlns在文档中.

It doesn't matter that the XPath expression uses a prefix where the original document didn't, as long as the namespace URI that is bound to the prefix in the XPath namespace context is the same as the URI that is bound by xmlns in the document.

这篇关于使用XOM在具有默认名称空间的xml上应用xpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆