问题
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);}
回答1:
Rather than loading your document in the constructor you should create some sub processes, such as
- Load the XML from the file into a
Document
- Create/Update your GUI, given a
Document
parameter
来源:https://stackoverflow.com/questions/28015467/how-do-you-instantly-update-an-xml-document-after-you-add-a-node-to-it