Click here to Skip to main content
16,021,823 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do I store the form data in xml by jsp. I tried but it doesnt get appended. Every time it overwrites or creates a new xml tag. Please help me

This is my code:
Java
<%@page import="java.io.*,org.w3c.dom.*,javax.xml.parsers. *,javax.xml.transform.*, javax.xml.transform.dom.*,javax.xml.transform.stream.*,javax.xml.*;"%>
<%!

public void createXmlTree(String name) throws Exception {
Element root;
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
File file = new File("/home/subham/new.xml");
if (file.exists())
{
//DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
//DocumentBuilder builder = fact.newDocumentBuilder();
doc = docBuilder.parse(file);
root = doc.getDocumentElement();
String sr = root.getNodeName();


//root = node.getNodeName();
}
else
{

root = doc.createElement("queries");
doc.appendChild(root);
}

Element child = doc.createElement("query");
root.appendChild(child);

Text text1 = doc.createTextNode(name);
child.appendChild(text1);

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();
}%>


<%
String query;

query = request.getParameter("searchquery");

try
{
//System.out.println(name);
// DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
//DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
// Document doc = docBuilder.newDocument();


createXmlTree(query);
response.sendRedirect("results.jsp");
}
catch(Exception e)
{
System.out.println(e);
}

%>
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900