javaxml-namespacesxom

Applying xpath on XML where namespaces are with children with XOM


I'm using XOM library to parse xmls. I have the following XML

<ns4:parent xmlns:ns4="http://sample.xml.com/ns4">
    <ns4:child1 xmlns:ns1="http://sample.xml.com/ns1" xmlns:xsi="http://sample.xml.com/xsi">
        <ns1:child2>divaStatus</ns1:child2>
        <xsi:child>something</xsi:child>
    </ns4:child1>
</ns4:parent>

And I want to apply a xpath like ns4:parent/ns4:child1/ns1:child2. So my code is like below

Document doc = new Builder().build(inStream);  //inStream is containing the xml
XPathContext xc = XPathContext.makeNamespaceContext(doc.getRootElement());
doc.query("ns4:parent/ns4:child1/ns1:child2", xc);

And I'm getting XPathException here.

 Exception in thread "main" nu.xom.XPathException: XPath error: XPath expression uses unbound namespace prefix ns1.

I can understand that since im making the namespace context by Root Element only, its not getting the namespaces of its children. So one work around might be traversing through all the children and collecting their namespaces and add it into the XpathContext object. But my xml can be of 10 to 20k lines. So Im afraid that how efficient the traversal approach will be.

Looking forward for any better suggestion


Solution

  • This is easy (or as easy as it can be, given the design of XPath and XML Namespaces). You just need to add any namespaces you want to use to the context manually. For instance, in this case,

    XPathContext xc = new XPathContext();
    xc.addNamespace("ns4", "http://sample.xml.com/ns4");
    xc.addNamespace("ns1", "http://sample.xml.com/ns1");
    doc.query("ns4:parent/ns4:child1/ns1:child2", xc);
    

    Note that you do not have to use the same prefixes in the XPath expression that the document uses.