XML Document to String?

前端 未结 2 439
無奈伤痛
無奈伤痛 2020-11-28 11:03

I\'ve been fiddling with this for over twenty minutes and my Google-foo is failing me.

Let\'s say I have an XML Document created in Java (org.w3c.dom.Document):

2条回答
  •  旧时难觅i
    2020-11-28 11:33

    You can use this piece of code to accomplish what you want to:

    public static String getStringFromDocument(Document doc) throws TransformerException {
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        return writer.toString();
    }
    

提交回复
热议问题