So I have an XML file here, and I want to get a value from it using XPath. The file in question is an XML file in a zip that you can download here:
I believe that it’s valid XML.
My current goal is to parse out the last (newest) LMP_PRC value in the document.
My current code looks like this and returns an empty string every time:
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr =
xpath.compile("//m:OASISReport/m:MessagePayload/m:RTO/m:REPORT_ITEM[3]/m:REPORT_DATA[/m:DATA_ITEM='LMP_PRC'][last()]/m:VALUE/text()") ;
String result = (String) expr.evaluate(doc, XPathConstants.STRING);
The m:REPORT_ITEM[3] has been an area of confusion for me so I’ve tried it with just about every number and have had no luck with it.
The m:REPORT_ITEM[3] just means the 3rd one that matches. You’re not getting any matches because of:
You want the relative path from there, not the absolute path:
So the whole thing would look like:
The other thing to deal with is the namespace resolution. For a good summary of what is happening in your case, see http://blog.davber.com/2006/09/17/xpath-with-namespaces-in-java/. So you should add something like:
And then use that method to set the namespace context on your
xpathobject: