Tuesday 11 July 2017

'
 Code TO Parse XML  Using Apex Through DOM
public  class Xmlparsar
{
    //xml string
    public String xmlstring{get;set;}
  
    //display xml string
    public String outxmlstring{get;set;}
  
    //rootelement
    public String rootElement{get;set;}
  
    //
    public String filename{get;set;}
  
    public blob body{get;set;}
     
    //constructor
    public Xmlparsar()
    {
   
    }
  
   
//Parsing xml what you entered in the left text area
    public pagereference Parsexml()
    {
       DOM.Document xmlDOC = new DOM.Document();
       xmlDOC.load(xmlstring);
       DOM.XMLNode rootElement = xmlDOC.getRootElement();
       outxmlstring=String.valueof(xmlDOC.getRootElement().getName());
      
       for(DOM.XMLNode xmlnodeobj:xmlDOC.getRootElement().getChildElements())
       //.getChildren())
       {       
        
         if(xmlnodeobj.getChildElements().size()== 0)
          {
          outxmlstring+='\n'+xmlnodeobj.getName()+': '+xmlnodeobj.getText();
      
          }
          System.debug(xmlnodeobj);
          loadChilds(xmlnodeobj);        
       }
       
            
       return null;
    }
  
    //loading the child elements
    public void loadChilds(DOM.XMLNode xmlnode)
    {

        
         if(xmlnode.getChildElements().size()>0){
          outxmlstring+='\n'+xmlnode.getName();
        }
       
        for(Dom.XMLNode child : xmlnode.getChildElements())
        {
         
         
          if(child.getText()!= null)
          {
          outxmlstring+='\n'+child.getName()+': '+child.getText();
      
          }
          loadChilds(child);      
        }
        System.debug(xmlnode.getChildElements());
       
    
    }
  
  

}

VisualForce Page
<apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Parse Xml" action="{!Parsexml}" />  
            </apex:pageBlockButtons>
            <apex:inputTextArea value="{!xmlstring}" style="width:336px;height:260px;"/> &nbsp;&nbsp;
            <apex:inputTextArea value="{!outxmlstring}" style="width:336px;height:260px;" id="response"/><br/>
        </apex:pageBlock>
    </apex:form>