【问题标题】:Modify XML file using Java使用 Java 修改 XML 文件
【发布时间】:2018-04-10 11:13:12
【问题描述】:

我想使用 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>

【问题讨论】:

    标签: java xml xslt


    【解决方案1】:

    在这段代码中:

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

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

     nList.appendChild(newserver);
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 2012-04-02
      • 1970-01-01
      相关资源
      最近更新 更多