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