如何使用新的子元素更新现有的xml文件

时间:2019-04-02 06:19:52

标签: java xml

我正在尝试将新的子元素添加到现有XML文件中。它正在添加,但是xml格式不正确

我正在使用SAXBuilder解析xml文件

public static void main(String[] args) throws JDOMException, IOException {
    Document document = null;
    Element root = null;

    File xmlFile = new File("Sample.xml");
    FileInputStream fis = new FileInputStream(xmlFile);
    // create a sax builder to parse the document
    SAXBuilder sb = new SAXBuilder();
    // parse the xml content provided by the file input stream and create a Document object
    document = sb.build(fis);
    // get the root element of the document
    root = document.getRootElement();
    System.out.println(root.getChildren());
    fis.close();


    root.addContent(newChild());
    document.setContent(root);

    FileWriter writer = new FileWriter("products.xml");
    XMLOutputter outputter = new XMLOutputter();
    outputter.output(document, writer);
    writer.close(); // close writer
}

protected static String newChild() throws JDOMException, IOException{
    StringBuilder sbFeatureInfo = new StringBuilder();
    sbFeatureInfo.append("\t<Feature id=\"123\">\n");
    sbFeatureInfo.append("\t\t<id>123</id>\n");
    sbFeatureInfo.append("\t\t<type>test</type>\n");
    sbFeatureInfo.append("\t</Feature>\n");


    return sbFeatureInfo.toString();
}

输出

<?xml version="1.0" encoding="UTF-8"?> </PC> <Feature id="1"> <id>1</id> <type>LF</type> </Feature> &lt;Feature id="123"&gt; &lt;id&gt;123&lt;/id&gt; &lt;type&gt;test&lt;/type&gt; &lt;/Feature&gt; </PC>

1 个答案:

答案 0 :(得分:0)

请尝试使用下面给出的代码。

注意:这只是一个提示,而不是已编译的代码。

Element feature  = document.createElement("Feature ");    
Element id = document.createElement("id");
id.appendChild(document.createTextNode(...));
feature.appendChild(id);          
root.appendChild(feature);