14

I am using this code to parsing xml

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(data));
    Document doc = db.parse(is);

Now I want to get all content from a xml node. Like from this xml

<?xml version='1.0'?>
<type>
  <human>                     
    <Name>John Smith</Name>              
    <Address>1/3A South Garden</Address>    
  </human>
</type>

So if want to get all content of <human> as text.

<Name>John Smith</Name>
<Address>1/3A South Garden</Address>

How can I get it ?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Barun
  • 1,885
  • 3
  • 27
  • 47

2 Answers2

33
private String nodeToString(Node node) {
  StringWriter sw = new StringWriter();
  try {
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    t.transform(new DOMSource(node), new StreamResult(sw));
  } catch (TransformerException te) {
    System.out.println("nodeToString Transformer Exception");
  }
  return sw.toString();
}
Rupok
  • 2,062
  • 16
  • 16
  • The dzone link posted above by @ObenSonne looks taken down (returns a 410 for me), so thanks for posting the code here! – user Oct 08 '18 at 17:48
  • Can you elaborate what you're doing? I have the same question but this answer doesn't work: (following OP example) my resulting String always contains the `` start and end tags and I need it without. – Mark Jeronimus Apr 09 '20 at 20:53
  • Worked for me. I was not able to print DOM Nodes as their tags appear in the xml. This function allowed me to do just that. – Prem P. Jul 17 '20 at 17:24
0

Besides Transformer it's also possible to use LSSerializer. For large nodes this serializer is faster.

Example:

    public static String convertNodeToString(Node node) {

        DOMImplementationLS lsImpl = (DOMImplementationLS)node.getOwnerDocument().getImplementation().getFeature("LS", "3.0");
        LSSerializer lsSerializer = lsImpl.createLSSerializer();

        DOMConfiguration config = lsSerializer.getDomConfig();
        config.setParameter("xml-declaration", Boolean.FALSE);

        return lsSerializer.writeToString(node);

   }
user2209562
  • 244
  • 2
  • 16