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

这一生的挚爱 提交于 2019-12-02 22:51:13

问题


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


来源:https://stackoverflow.com/questions/28015467/how-do-you-instantly-update-an-xml-document-after-you-add-a-node-to-it

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