如何使用JSP将表单数据存储在XML中

时间:2016-05-09 05:27:24

标签: xml jsp

如何使用JSP将表单数据存储在XML中?我试过了,但没有追加。每次覆盖文件或创建新的XML标记。

query.jsp:

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

每次创建新的XML页面时。我想要创建一个XML页面并附加数据,我不知道如何进行更改,因为我不熟悉XML和JSP。有人能告诉我需要做些什么改变吗?

0 个答案:

没有答案