Barun
Barun

Reputation: 1915

java - Getting all content of a xml node as string

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 ?

Upvotes: 14

Views: 19068

Answers (2)

skin27
skin27

Reputation: 426

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);

   }

Upvotes: 0

Rupok
Rupok

Reputation: 2082

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();
}

Upvotes: 34

Related Questions