0

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

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

如果这可能,请为此编码。

4

1 回答 1

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 页面,例如。新的.jsp

更改文件名 str="want u want" 并更改属性attr.setValue("want u want");

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

于 2012-07-13T16:04:42.087 回答