简体   繁体   中英

Get XML value from xpath with namespace

To be clear, my xml and its XPath are dynamic, anything may come, so no hard coded values to parse XML value from XPath. Here is my XML and XPath constructed.

String xml = "<soapenv:Envelope xmlns:com=\"http://com\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Header/><soapenv:Body><com:addition><com:a>1</com:a><com:b>1</com:b></com:addition></soapenv:Body></soapenv:Envelope>";
Document doc = UtilityFunction.createXMLDocument(xml);
System.out.println("Value "+XPathFactory.newInstance().newXPath().compile("//soapenv:Envelope[1]/soapenv:Body[1]/com:addition[1]/com:a[1]").evaluate(doc).toString());

Empty is getting printed. How can I use namespace to get XML value from xpath. How to enable namespace in compilation.

XPathFactory.newXPath() returns an XPath object.

Create a NamespaceContext object, set it up to know about your namespace bindings, and call .setNamespaceContext() on the XPath object.

Then compile the XPath and invoke as usual.

(I presume this duplicates answers given in some of the "Related" questions at right, so I'm not going to give a code sample. It's simple enough.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM