在向其添加节点后,如何立即更新XML文档? [英] How do you instantly update an XML document after you add a node to it?

查看:79
本文介绍了在向其添加节点后,如何立即更新XML文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

声明:

    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 ,然后文件更新如下:

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


推荐答案

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

Rather than loading your document in the constructor you should create some sub processes, such as


  1. 将文件中的XML加载到文档

  2. 创建/更新GUI,给定文件参数

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

这篇关于在向其添加节点后,如何立即更新XML文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆