我正在尝试将从表单中获取的一些数据写入XML文件,每次我想要创建新文件并写入数据时我希望这些文件存储在特定文件夹中这就是我所拥有的试过。我想通过httpRequest成功添加我收到的任何内容
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String hostIPAddress=request.getParameter("hostIPAddress");
String destinationIPAddressTool1=request.getParameter("IPtool1");
String destinationIPAddressTool2=request.getParameter("IPtool2");
String root="root";
String hostIPElement="Host-IP";
String tool1Element="Tool-1";
String tool2Element="Tool-2";
if(destinationIPAddressTool1 == null)
{
destinationIPAddressTool1="none";
}
if(destinationIPAddressTool2 == null)
{
destinationIPAddressTool2="none";
}
DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = null;
try {
documentBuilder = documentBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement(root);
document.appendChild(rootElement);
Element em1 = document.createElement(hostIPElement);
em1.appendChild(document.createTextNode(hostIPAddress));
rootElement.appendChild(em1);
Element em2 = document.createElement(tool1Element);
em2.appendChild(document.createTextNode(destinationIPAddressTool1));
rootElement.appendChild(em2);
Element em3 = document.createElement(tool2Element);
em3.appendChild(document.createTextNode(destinationIPAddressTool2));
rootElement.appendChild(em3);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
try {
transformer.transform(source, result);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
答案 0 :(得分:1)
这里试试这最终应该有效
//将内容写入xml文件
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("file.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);