How to I output org.w3c.dom.Element to string format in java?

前端 未结 7 676
旧巷少年郎
旧巷少年郎 2020-11-27 13:01

I have an org.w3c.dom.Element object passed into my method. I need to see the whole xml string including its child nodes (the whole object graph). I am looking

7条回答
  •  一整个雨季
    2020-11-27 13:45

    Assuming you want to stick with the standard API...

    You could use a DOMImplementationLS:

    Document document = node.getOwnerDocument();
    DOMImplementationLS domImplLS = (DOMImplementationLS) document
        .getImplementation();
    LSSerializer serializer = domImplLS.createLSSerializer();
    String str = serializer.writeToString(node);
    

    If the declaration bothers you, you could use a transformer instead:

    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer();
    StringWriter buffer = new StringWriter();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.transform(new DOMSource(node),
          new StreamResult(buffer));
    String str = buffer.toString();
    

提交回复
热议问题