How do you instantly update an XML document after

2019-03-06 20:41发布

问题:

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

  1. Load the XML from the file into a Document
  2. Create/Update your GUI, given a Document parameter