我想使用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>
答案 0 :(得分:1)
在此代码中:
Node nList = doc.getDocumentElement().getChildNodes().item(0).getLastChild();
选择最后一个field
元素,然后:
nList.appendChild(newserver);
将您的新元素添加为最后一个field
元素的子元素。
您希望新节点成为fields-mapping
元素的子节点,因此请尝试删除不需要的.getLastChild()
。