Need help with xPath expressions with namespaces

I need help with 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 break pattern to retrieve data.

This is where I use the 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 a base to my namespace map as follows:

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 a Response node, and I can expand the child nodes using .getChildNodes and creating nodelists for each child.

I would like to get the hello value directly using the xpath expression, but I cannot get it to work with anything other than the base: *. Can someone help me with my expression?

thank

+3
source share
3 answers

This is an XPath expression:

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

, base http://schemas.test.com/search/local/ws/rest/v1 URI .

+5

hello = xpathTemplate.evaluateAsString("//*[local-name()='nodeTest']", source);

+2

Try the following:

xpathTemplate.evaluate("/Response/nodeB/nodeb1/nodeb1a/nodeTest", ...

If you need more information about XPath, you can try the following http://www.zvon.org/xxl/XPathTutorial/General/examples.html

My site also offers a tool to check your xpath requests: http://ap2cu.com/tools/xpath/index.php5

-1
source

Source: https://habr.com/ru/post/1795771/


All Articles