所以我有以下代码,我想在其中创建一个 XML 文件并将其存储在本地计算机上,但是每当我执行代码时,它似乎并没有保存文件,有人可以帮我吗?
public void CreateXMLPoll (Poll p) {
try {
// Initialize the XML builder
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
// Set the Elements Up
Element rootElement = doc.createElement("Poll");
Element creator = doc.createElement("Creator");
Element name = doc.createElement("Name");
Element email = doc.createElement("Email");
Element title = doc.createElement("Title");
Element location = doc.createElement("Location");
Element description = doc.createElement("Description");
Element date = doc.createElement("Date");
Element time = doc.createElement("Time");
// Create XML tree
rootElement.appendChild(creator);
rootElement.appendChild(title);
rootElement.appendChild(location);
rootElement.appendChild(description);
rootElement.appendChild(date);
creator.appendChild(name);
creator.appendChild(email);
date.appendChild(time);
// Add values to XML
name.appendChild(doc.createTextNode(p.getUsername()));
email.appendChild(doc.createTextNode(p.getEmail()));
title.appendChild(doc.createTextNode(p.getTitle()));
location.appendChild(doc.createTextNode(p.getLocation()));
description.appendChild(doc.createTextNode(p.getDescription()));
// Appends a bunch of dates
for (PollDates pd : p.getDates()) {
time.appendChild(doc.createTextNode(pd.getFirst().toString()));
if (pd.getSecond() != null) time.appendChild(doc.createTextNode(pd.getSecond().toString()));
if (pd.getThird() != null) time.appendChild(doc.createTextNode(pd.getThird().toString()));
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
try {
Transformer transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
}
FileWriter fstream = new FileWriter("test.xml");
BufferedWriter out = new BufferedWriter(fstream);
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:/Users/testing.xml"));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我按照这里的教程进行操作。