英文:
Parsing XML with java - does not get all xml values
问题
尝试解析 XML 以获取“CreDtTm”标签的值,以下是解析和编辑 XML 的方法(暂时跳过写回 XML 文件的部分):
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); // **这个会变成 null**
node.setTextContent(entry.getValue());
}
基本上,<CreDtTm>
标签未被找到,而且 node
变量被设置为 null
。不太清楚原因是什么?能帮我解决一下吗?
(注意:上面的翻译是你提供的内容的直接翻译,没有进行额外的解释或添加。)
英文:
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 <CreDtTm> tag is not found and node variable is set to null.
Not sure why? Can you help me out?
答案1
得分: 1
运行您的示例代码使我相信您在tagValuesToChange
映射中的键是标签的名称,而不是有效的XPath表达式。请尝试使用//CreDtTm
作为映射的键,然后查看是否有效。
当我将标签名称用作映射键时,我能够复现NullPointerException
。使用我提供的XPath表达式,代码能够找到节点并更新文本内容。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论