Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help with xPath expressions with namespaces

I need some help with a xpath expression.

I have the following xml document:

<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          xmlns="http://schemas.test.com/search/local/ws/rest/v1">
    <nodeA>text</nodeA>
    <nodeB>
        <nodeb1>
            <nodeb1a>
                <nodeTest>hello</nodeTest>
            </nodeb1a>
        </nodeb1>
    </nodeB>
</Response>

I am using Springs rest template to retrieve the data.

Here is where I am using a xpath expression to get the node values:

xpathTemplate.evaluate("base:*", xmlSource, new NodeMapper() {
        public Object mapNode(Node node, int i) throws DOMException {
            Element response = (Element) node;
            System.out.println("hi: " + response.getTextContent());

I added base to my namespace map like this:

HashMap<String, String> nameSpaces = new HashMap<String, String>();
nameSpaces.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");
nameSpaces.put("xsd", "http://www.w3.org/2001/XMLSchema");
nameSpaces.put("base", "http://schemas.test.com/search/local/ws/rest/v1");
((Jaxp13XPathTemplate) xpathTemplate).setNamespaces(nameSpaces);

Using the expression base:* gives me the Response node and I am able to drill down to the child nodes using .getChildNodes and creating nodelists for each child.

I would like to get the hello value directly with the xpath expression but I am not able to get it to work with anything but base:*. Can someone help me with my expression?

Thanks

like image 935
blong824 Avatar asked Apr 12 '26 16:04

blong824


1 Answers

This XPath expression:

/base:Response/base:nodeB/base:nodeb1/base:nodeb1a/base:nodeTest

Assuming base is bound to http://schemas.test.com/search/local/ws/rest/v1 namespace URI.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!