Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse XML with XPath & namespaces in Java

Tags:

java

xml

xpath

Can you help me adjust this code so it manages to parse the XML? If I drop 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");
like image 440
ripper234 Avatar asked May 12 '10 11:05

ripper234


1 Answers

  1. You must use a prefix in your XPath, e. g.: "/my:foo/my:bar" You can choose any prefix you like - it doesn't have anything to do with the prefixes you use or don't use in the XML file - but you must choose one. This is a limitation of XPath 1.0.

  2. You must perform prefix mapping from "my" to "http://foo.bar/boo" (not to "http://www.w3.org/2001/XMLSchema-instance")

like image 80
Chris Lercher Avatar answered Nov 09 '22 23:11

Chris Lercher