简体   繁体   中英

Parsing XML with java - does not get all xml values

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?

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.

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