在Servlet中执行XML

时间:2015-06-03 02:26:17

标签: java xml servlets

我的java类中有一个方法,它下载一个XML文件并返回一个org.w3c.dom.Document对象。

我想从这个java servlet类中获取这个XML,但是无法弄清楚如何。

我试过了:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        Document document = Allmethods.getXML();

        response.setContentType("text/xml;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write(document);

    }

但它不起作用,因为printwriter不适用于文档对象。我该如何存档?

1 个答案:

答案 0 :(得分:0)

我成功地听了@Jim Garrison的提示。

Document document = Allmethods.getXML();

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(writer));
        String output = writer.getBuffer().toString();

        response.setContentType("text/xml;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write(output);