gpt4 book ai didi

java - 使用 Java 修改 XML 文件

转载 作者:行者123 更新时间:2023-11-30 10:17:15 25 4
gpt4 key购买 nike

我想使用 Java 在现有 XML 文件的最后一行添加一个节点。所以我遵循了下面的代码。

示例 XML 文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<mapping-configuration>
<fields-mapping>
<field compare="true" criteria="true" displayName="demo1"/>
<field compare="true" criteria="true" displayName="demo2"/>
</fields-mapping>
</mapping-configuration>

代码:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("C:/Desktop/test.xml"));
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
Node nList = doc.getDocumentElement().getChildNodes().item(0).getLastChild();
System.out.println(nList.getNodeName());
Element newserver=doc.createElement("field");
newserver.setAttribute("source", "33");
nList.appendChild(newserver).normalize();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:/Desktop/test.xml"));
transformer.transform(source, result);

所以,我得到了结果作为

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<mapping-configuration>
<fields-mapping>
<field compare="true" criteria="true" displayName="demo1"/>
<field compare="true" criteria="true" displayName="demo2">
<field source="33"/>
</field>
</fields-mapping>
</mapping-configuration>

但我的预期输出应该是

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<mapping-configuration>
<fields-mapping>
<field compare="true" criteria="true" displayName="demo1"/>
<field compare="true" criteria="true" displayName="demo2"/>
<field source="33"/>
</fields-mapping>
</mapping-configuration>

最佳答案

在这段代码中:

Node nList = doc.getDocumentElement().getChildNodes().item(0).getLastChild();

选择最后一个 field 元素,然后:

 nList.appendChild(newserver);

将您的新元素添加为最后一个 field 元素的子元素。

您希望新节点作为 fields-mapping 元素的子节点,因此请尝试删除不需要的 .getLastChild()

关于java - 使用 Java 修改 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49752181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com