How do you instantly update an XML document after you add a node to it?



So I'm making a calendar program and I need it to update when you add a new entry to it. Right now, I need to click on the xml file to get it to update, then everything else works fine.


Declaration:



private DocumentBuilderFactory documentFactory;
private DocumentBuilder documentBuilder;
private Document xmlDoc;
private Node rootNode;
private static Node dataNode;


Assignment in constructor:



try {
documentFactory = DocumentBuilderFactory.newInstance();
documentBuilder = documentFactory.newDocumentBuilder();
xmlDoc = documentBuilder.parse(Main.class.getResourceAsStream("Calendar.xml"));
rootNode = xmlDoc.getDocumentElement();
dataNode = rootNode.getChildNodes().item(0);
} catch(ParserConfigurationException | SAXException | IOException e) {e.printStackTrace(System.out);}


Node is created and added to dataNode after a button is pressed, then the file is updated like this:



try {
OutputFormat outFormat = new OutputFormat(xmlDoc);

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

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

No comments:

Post a Comment