0

Here is some Java-Code:

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XpathQuestion {
public static void main(String[] args) throws SAXException, IOException, XPathExpressionException, ParserConfigurationException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);

    DocumentBuilder documentBuilder = factory.newDocumentBuilder();

    XPath xpath = XPathFactory.newInstance().newXPath();

    File xmlFile = new File("stackoverflow.xml");

    Document doc = documentBuilder.parse(new InputSource(xmlFile.getAbsolutePath()));

    NodeList nodes1 = (NodeList) (xpath.evaluate("//AB", doc,
            XPathConstants.NODESET));

    NodeList nodes2 = (NodeList) (xpath.evaluate("//AB/stat", doc,
            XPathConstants.NODESET));

    int nodes1Length = nodes1.getLength();
    int nodes2Length = nodes2.getLength();

    System.out.println(nodes1Length);
    System.out.println(nodes2Length);

}
}

The document stackoverflow.xml in the above code looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<ns:document xmlns:ns="http://www.noinfohere.de">
  <ns:env>
    <ns:trans>
      <ns:version>123</ns:version>
    </ns:trans>
    <ns:sender>
        <ns:senderId>abc</ns:senderId>
    </ns:sender>
  </ns:env>
      <ns:AB>
           <ns:stat>asdf</ns:stat>
      </ns:AB>
</ns:document>

When I run the program the ouput is:

0
1

Means: nodes1Length=0 and nodes2Length=1

What I don't understand is: why is nodes1Length=0? The xpath expression "//AB" should find all AB elements in the document. What's wrong with my program?

Thanx 4 your help.

moosey
  • 1
  • 2
  • Possible duplicate of [javax.xml, XPath is not extracted from XML with namespaces](http://stackoverflow.com/questions/23203421/javax-xml-xpath-is-not-extracted-from-xml-with-namespaces) – JLRishe Mar 24 '17 at 16:26
  • 1
    There are no `AB` elements in your document. They are `{http://www.noinfohere.de}AB` elements. Please see the link above. – JLRishe Mar 24 '17 at 16:27
  • @JLRishe Actually, due to the code’s invocation of `factory.setNamespaceAware(false)`, the document probably contains elements whose full name is `ns:AB`. – VGR Mar 24 '17 at 16:57

0 Answers0