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 ?

2 Answers 2

34
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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

The dzone link posted above by @ObenSonne looks taken down (returns a 410 for me), so thanks for posting the code here!
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 <human> start and end tags and I need it without.
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.
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);

   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.