Java xpath namespace resolution example

Namespace resolution in XPath allows you to specify namespaces for XML documents and helps in selecting the elements and attributes within a namespace.

Here is an example of using XPath in Java to resolve namespaces and select elements and attributes:

refer t‮igi:o‬ftidea.com
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.*;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import java.io.StringReader;
import java.util.Iterator;

public class XPathNamespaceExample {

    public static void main(String[] args) throws Exception {
        String xml = "<root xmlns:ns=\"http://example.com/ns\"><ns:child attr=\"value\">Text</ns:child></root>";

        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
        XPath xpath = XPathFactory.newInstance().newXPath();

        // Create a NamespaceContext to resolve the namespace URI and prefix
        NamespaceContext nsContext = new NamespaceContext() {
            @Override
            public String getNamespaceURI(String prefix) {
                return "http://example.com/ns";
            }

            @Override
            public String getPrefix(String namespaceURI) {
                return "ns";
            }

            @Override
            public Iterator getPrefixes(String namespaceURI) {
                return null;
            }
        };

        xpath.setNamespaceContext(nsContext);

        // Use the namespace prefix to select the element and its attribute
        XPathExpression expr = xpath.compile("/ns:root/ns:child/@attr");
        String result = (String) expr.evaluate(document, XPathConstants.STRING);

        System.out.println(result);
    }
}

In this example, we create an XML document with a child element within a namespace, and an attribute within that child element. We then use a NamespaceContext to resolve the namespace prefix ns to its corresponding URI, and set the XPath expression to select the attribute using that prefix. The result is the value of the attribute, which is printed to the console.