How do you update an XML file after you change a node? [duplicate]

霸气de小男生 提交于 2019-12-02 04:01:19

Replace...

OutputFormat outFormat = new OutputFormat(xmlDoc);
try (FileOutputStream outStream = new FileOutputStream("src/virtualagenda/Calendar.xml")) {
    XMLSerializer serializer = new XMLSerializer(outStream, outFormat);
    serializer.serialize(xmlDoc);

    outStream.close();
}catch(IOException e) {e.printStackTrace(System.out);}

With something more like...

Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty(OutputKeys.METHOD, "xml");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

try (FileOutputStream outStream = new FileOutputStream("Calendar.xml")) {
    DOMSource domSource = new DOMSource(document);
    StreamResult sr = new StreamResult(outStream );
    tf.transform(domSource, sr);
} catch (TransformerConfigurationException, TransformerException exp) {
    exp.printStackTrace();
}

Updated with runnable example

So using...

<?xml version="1.0" encoding="UTF-8"?>
<fruit>
    <banana>yellow</banana>
    <orange>orange</orange>
    <pear>yellow</pear>    
</fruit>

And then using...

try {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document document = builder.parse(new File("Calendar.xml"));

    NodeList nodeList = document.getDocumentElement().getChildNodes();
    for (int index = 0; index < nodeList.getLength(); index++) {
        Node node = nodeList.item(index);
        if (node.getNodeType() != Node.TEXT_NODE) {
            node.setTextContent("Some text");
        }
    }

    Transformer tf = TransformerFactory.newInstance().newTransformer();
    tf.setOutputProperty(OutputKeys.INDENT, "yes");
    tf.setOutputProperty(OutputKeys.METHOD, "xml");
    tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    try (FileOutputStream os = new FileOutputStream(new File("Calendar.xml"))) {

        DOMSource domSource = new DOMSource(document);
        StreamResult sr = new StreamResult(os);
        tf.transform(domSource, sr);

    }

} catch (SAXException | TransformerException | IOException | ParserConfigurationException ex) {
    ex.printStackTrace();
}

Outputs...

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<fruit>
    <banana>Some text</banana>
    <orange>Some text</orange>
    <pear>Some text</pear>    
</fruit>

The transformation code works, there is something else within your code which you're not showing us which isn't working...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!