Pages

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;

              xmlString="<";

              xmlString+=xmlNode.getNodeName();

             

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

              }

              xmlString+=">";

             

              NodeList childNodes=xmlNode.getChildNodes();

              int noOfChildNodes=childNodes.getLength();

             

              if (noOfChildNodes==0)     {

                     xmlString+=xmlNode.getNodeValue();

              }      else   {

                     int childNodeItr=0;

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

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

                     }

              }

             

              xmlString+="</"+xmlNode.getNodeName()+">";

             

              return xmlString;

       }

 

 

No comments:

Post a Comment