Thursday, June 5, 2014

getXMLString from an XML Node Object

Following is a simple function that would let you obtain the XML contents of a XML node in a string format. The packages that had been imported into the class are listed as follows. I hope these are available as a free download


import org.w3c.dom.NamedNodeMap;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;


public static String getXMLString(Node xmlNode){

              String xmlString = null;




              NamedNodeMap attributes=xmlNode.getAttributes();

              int noOfAttributes=attributes.getLength();

              int itr=0;


              for (itr=0;itr<noOfAttributes;itr++)     {

                     Node attributeNode=attributes.item(itr);

                     xmlString+=" "+ attributeNode.getNodeName() + "=" + attributeNode.getNodeValue();




              NodeList childNodes=xmlNode.getChildNodes();

              int noOfChildNodes=childNodes.getLength();


              if (noOfChildNodes==0)     {


              }      else   {

                     int childNodeItr=0;

                     for (childNodeItr=0;childNodeItr<noOfChildNodes;childNodeItr++)      {

                           xmlString += getXMLString(childNodes.item(childNodeItr));






              return xmlString;




No comments:

Post a Comment