XML Document to String

前端 未结 3 1395
余生分开走
余生分开走 2020-11-27 02:44

What\'s the simplest way to get the String representation of a XML Document (org.w3c.dom.Document)? That is all nodes will be on a single line.

As an ex

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 03:34

    Assuming doc is your instance of org.w3c.dom.Document:

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
    

提交回复
热议问题