在向其添加节点后,如何立即更新XML文档?

时间:2015-01-18 22:19:01

标签: java xml file-writing

所以我正在创建一个日历程序,当你向它添加一个新条目时我需要它来更新。现在,我需要点击xml文件让它更新,然后其他一切正常。

宣言:

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

构造函数中的赋值:

    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);}

创建节点并在按下按钮后将其添加到dataNode,然后文件更新如下:

    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 个答案:

答案 0 :(得分:0)

您应该创建一些子流程,例如

,而不是在构造函数中加载文档
  1. 将文件中的XML加载到Document
  2. 根据Document参数
  3. 创建/更新您的GUI