Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在带有XOM的默认命名空间的xml上应用xpath_Java_Xpath_Xml Namespaces_Xom - Fatal编程技术网

Java 在带有XOM的默认命名空间的xml上应用xpath

Java 在带有XOM的默认命名空间的xml上应用xpath,java,xpath,xml-namespaces,xom,Java,Xpath,Xml Namespaces,Xom,下面是包含默认名称空间的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&

下面是包含默认名称空间的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>
但大小始终为0

我经历了

  • [我真的不懂奇怪的xpath语法]
  • [可以看到一些希望。只需要对我当前的实施进行重大更改]

期待任何帮助。

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与文档中由
xmlns
绑定的URI相同。

得到了这一点非常有用-。尝试答案的更新部分。只是另一个提示,您必须添加xpath表达式中使用的所有标记的所有名称空间,而不仅仅是限定的名称空间。在我的例子中,问题是它缺少我的非限定命名空间的addNamespace:(
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());