I have an input XML provided through a String (it is an ISO20022 payment message) and I'd like to extract values for certain tags from that XML. Here is my source code:
package com.company;
import org.xml.sax.InputSource;
import javax.xml.xpath.*;
import java.io.StringReader;
public class Main {
public static void main(String[] args) throws XPathExpressionException {
String xmlStr = "<Document xmlns=\"urn:iso:std:iso:20022:tech:xsd:pacs.004.001.02\">\n" +
"\t<GrpHdr>\n" +
"\t\t<NbOfTxs>1</NbOfTxs>\n" +
"\t\t<InstgAgt>\n" +
"\t\t\t<FinInstnId>\n" +
"\t\t\t\t<BIC>MYBIC123</BIC>\n" +
"\t\t\t</FinInstnId>\n" +
"\t\t</InstgAgt>\n" +
"\t</GrpHdr>\n" +
"</Document>\n";
InputSource source = new InputSource(new StringReader(xmlStr));
XPath xpath = XPathFactory.newInstance().newXPath();
Object payment = xpath.evaluate("/", source, XPathConstants.NODE);
String tagValue = xpath.evaluate("/Document/GrpHdr/NbOfTxs", payment);
System.out.println("The message has "+tagValue+" txns");
}
}
However, I am not able to read value of NbOfTxs tag, unless the Document tag is replaced with something else, such as DummyRoot (and xmlns etc are dropped).
A quick and dirty solution is just to replace the substrings related to Document tag, but I would like to address the problem correctly.