我正在尝试使用JSP将表单数据存储在XML文件中。但是,输入多个条目后,我得到了重复的行:
(似乎附加了记录2,记录2之前的整个事情被重写)
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Students>
<Name>test1</Name>
<Title>balala</Title>
<URL>www.kaka.com</URL>
</Students>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Students>
<Name>test1</Name>
<Title>balala</Title>
<URL>www.kaka.com</URL>
<Name>test2</Name>
<Title>nana</Title>
<URL>www.lolo.com</URL>
</Students>
我正在使用的代码:
<body>
<h3>Get Data from the form</h3>
<p>
<%
//Get data from the form
String name= request.getParameter("name");
String title=request.getParameter("title");
String url= request.getParameter("url");
%>
<%!
public void createXmlTree(String name,String title,String url) throws Exception {
Element root;
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
File file = new File("C:/Users/webservstu/Documents/new.xml");
if (file.exists())
{
doc = docBuilder.parse(file);
root = doc.getDocumentElement();
String sr = root.getNodeName();
}
else
{
System.out.println(name);
root = doc.createElement("Students");
doc.appendChild(root);
}
Element child1 = doc.createElement("Name");
root.appendChild(child1);
Text text1 = doc.createTextNode(name);
child1.appendChild(text1);
Element child2 = doc.createElement("Title");
root.appendChild(child2);
Text text2 = doc.createTextNode(title);
child2.appendChild(text2);
Element child3 = doc.createElement("URL");
root.appendChild(child3);
Text text3 = doc.createTextNode(url);
child3.appendChild(text3);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = sw.toString();
FileWriter fw=new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(xmlString);
bw.flush();
bw.close();
}%>
<%
try
{
createXmlTree(name,title,url);
out.println("<b>Xml File Created Successfully</b>");
}
catch(Exception e)
{
System.out.println(e);
}
%>
<br>
</p>
<hr>
<p><font size="2">*Direct Submission*</font></p>
</body>
有什么想法?感谢!!!
答案 0 :(得分:0)
这是问题所在:
FileWriter fw=new FileWriter(file,true);
你的第二个论点是追加到文件的末尾。
另一方面,我建议不要改变这一点 - 我建议改为使用FileOutputStream
并直接创建StreamResult
,所以它会直接写 / em>到该文件没有任何其他编码妨碍。实际上,您将使用平台默认编码来编写文本,即使文本本身声明它是UTF-8。
哎呀,你甚至不需要自己创建FileOutputStream
- 你可以直接从StreamResult
创建File
。