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.