Reputation: 105
Trying to parse xml to get "CreDtTm" tag value from this XML (pasted not the whole):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
<CstmrCdtTrfInitn>
<GrpHdr>
<MsgId>SANDISS_2020_10_08_001</MsgId>
<CreDtTm>2020-10-15T18:15:33</CreDtTm>
<NbOfTxs>3</NbOfTxs>
<CtrlSum>36.00</CtrlSum>
<InitgPty>
<Nm>Bank</Nm>
<Id>
<OrgId>
<Othr>
<Id>40100</Id>
<SchmeNm>
<Cd>COID</Cd>
</SchmeNm>
</Othr>
</OrgId>
</Id>
</InitgPty>
</GrpHdr>
However, getting not all values
Here is the method for parsing and editing xml (writing back to XML file is skipped atm)
public void modifyXmlFile(String filePath, Map<String, String> tagValuesToChange) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document document = docBuilder.parse(filePath);
XPath xpath = XPathFactory.newInstance().newXPath();
for (Map.Entry<String, String> entry : tagValuesToChange.entrySet()) {
Node node = (Node) xpath.compile(entry.getKey()).evaluate(document, XPathConstants.NODE); //**This becomes null**
node.setTextContent(entry.getValue());
}
Basically tag is not found and node variable is set to null. Not sure why? Can you help me out?
Upvotes: 0
Views: 259
Reputation: 613
Running you sample leads me to believe your key in the tagValuesToChange
Map is the name of the tag and not a valid XPath expression. Try using //CreDtTm
as the key to your map, and see if that works.
I was able to reproduce the NullPointerException
when I used the name of the tag as the Map key. Using the XPath expression I suggested, the code was able to find the node and update the text content.
Upvotes: 1