Parse XML with XPath and Namespaces in Java

Can you help me tweak this code so that it can parse XML? If I omit the XML namespace, it works:

String webXmlContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                       "<foo xmlns=\"http://foo.bar/boo\"><bar>baz</bar></foo>";
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(new StringInputStream(webXmlContent));

NamespaceContextImpl namespaceContext = new NamespaceContextImpl();
namespaceContext.startPrefixMapping("foo", "http://www.w3.org/2001/XMLSchema-instance");
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(namespaceContext);

XPathExpression expr = xpath.compile("/foo/bar");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println("Got " + nodes.getLength() + " nodes");
+5
source share
1 answer
  • You must use the prefix in XPath, eg: "/ my: foo / my: bar" You can choose any prefix that you like - it has nothing to do with the prefixes that you use or do not use in the XML file, but you must choose one of them. This is a limitation of XPath 1.0.

  • "my" " http://foo.bar/boo" ( " http://www.w3.org/2001/XMLSchema-instance" )

+9

All Articles