所以我正在创建一个日历程序,当你向它添加一个新条目时我需要它来更新。现在,我需要点击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);}
答案 0 :(得分:0)
您应该创建一些子流程,例如
,而不是在构造函数中加载文档Document
Document
参数