使用jsp编码创建xml文件并存储在本地磁盘文件夹中

时间:2012-07-13 15:42:04

标签: jsp

我可以使用jsp编码创建一个xml文件,并将其存储到具有我们指定名称的本地磁盘中。 这样的xml文件结构

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<questions>
<question category="something"/>
</questions>

如果可能,请为此编码。

1 个答案:

答案 0 :(得分:1)

<%@page import="java.io.*,org.w3c.dom.*,javax.xml.parsers.*,javax.xml.transform.*, javax.xml.transform.dom.*,javax.xml.transform.stream.*"%>  
<%!
public void createXml(String graph) throws Exception{
try{
    String str="dinesh";
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    // questionset elements
    Element rootElement = doc.createElement("questionset");
    doc.appendChild(rootElement);
    // question elements
    Element question = doc.createElement("question");
    rootElement.appendChild(question);
    // set attribute to question element
    Attr attr = doc.createAttribute("category");
    attr.setValue("graph");
    question.setAttributeNode(attr);
    // write the content into xml file        

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

    File file=new File("C:xml/"+str+".xml");
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    bw.write(xmlString);
    bw.flush();
    bw.close();
}
catch(Exception e)
{
System.out.println(e);
}   
}
%>
<% 
String graph=request.getParameter("graph");
createXml(graph);
%>

将上述编码保存为任何jsp页面,例如。 new.jsp

更改文件名str =“想要你想要” 并且还更改属性attr.setValue("want u want");

您还可以更改文件要保存的本地磁盘文件夹