我正在使用以下代码在我的一个项目中使用Stax Parser创建XML文件。我之前在普通的java应用程序中使用过这段代码,并在那里运行良好。但是当我为Servlet实现这个时,我不知道为什么它没有运行。我没有收到任何错误,但未生成 XML 文件。
private static ServletContext sc;
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
sc = config.getServletContext();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = sc.getRealPath("/WEB-INF/xml");
System.out.println("Path ==>" + path);
XMLOutputFactory factory = XMLOutputFactory.newInstance();
File f = new File(path+"/atms.xml");
XMLStreamWriter writer = factory.createXMLStreamWriter(new FileOutputStream(f));
//Some more code
writer.writeStartDocument();
writer.writeStartElement("xxx");
writer.writeStartElement("yyy");
writer.writeStartElement("id");
writer.writeCharacters("1");
writer.writeStartElement("name");
writer.writeCharacters("Table");
writer.writeStartElement("price");
writer.writeCharacters("110");
writer.writeEndElement();
writer.close();
}
答案 0 :(得分:0)
我认为您需要添加以下内容:
writer.writeEndElement();
writer.writeEndDocument();
writer.flush();
writer.close();