-1

所以我正在制作一个日历程序,当您向其中添加新条目时,我需要更新它。现在,我需要单击 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);}
4

1 回答 1

0

而不是在构造函数中加载您的文档,您应该创建一些子流程,例如

  1. 将文件中的 XML 加载到Document
  2. Document给定一个参数,创建/更新您的 GUI
于 2015-01-18T22:28:39.847 回答