Applying xpath on xml with default namespace with XOM

元气小坏坏 提交于 2019-12-10 15:27:27

问题


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());

But the size is always 0.

I gone through

  • 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]

Looking forward for any help.


回答1:


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());

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.



来源:https://stackoverflow.com/questions/14336587/applying-xpath-on-xml-with-default-namespace-with-xom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!