Monday, 3 June 2013

XML Parsing

Hi,
I am going to give a brief explanation on xml parsing.we have DOM parser to parse xml.
Before we are going to parse an xml file we need to look its strcture and we should expect how many we may need for parsing the "XML" which have to avoid number of  script statemements limitation in Apex.
Use the XmlNode class to work with a node in an XML document. The DOM represents an XML document as a hierarchy of nodes. Some nodes may be branch nodes and have child nodes, while others are leaf nodes with no children.
Node Types
There are different types of DOM nodes available in Apex. XmlNodeType is an enum of these different types. The values are:
COMMENT
ELEMENT
TEXT
It is important to distinguish between elements and nodes in an XML document. The following is a simple XML example:
<name>
    <firstName>Balaji</firstName>
    <lastName>Malemarpuram</lastName>
</name>
This example contains three XML elements: name, firstName, and lastName. It contains five nodes: the three name, firstName, and lastNameelement nodes, as well as two text nodes—Balaji and Marpuram. Note that the text within an element node is considered to be a separate text node.
Example:
======
public  class Xmlparsercls {
    public String xmlstring{get;set;}
    public String outxmlstring{get;set;}
    public String rootElement{get;set;}
    public String filename{get;set;}
    public blob body{get;set;}
    public List<Account> lstaccount{get;set;}
    public Xmlparsercls(){
      lstaccount=new List<Account>();
    }
//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()){
          if(xmlnodeobj.getName()=='Name')
            outxmlstring+='\nAccount Name:'+xmlnodeobj.getText();
          if(xmlnodeobj.getName()=='Type')
            outxmlstring+='\nAccount Type:'+xmlnodeobj.getText();  
          if(xmlnodeobj.getName()=='Industry')
            outxmlstring+='\nAccount Industry:'+xmlnodeobj.getText();
       }
       
      return null;
    }
//This is for parsing xml file what you selected
  public pagereference Parsexmlfile(){
       DOM.Document xmlDOC = new DOM.Document(); 
       xmlstring=body.tostring();
       system.debug('****xmlstring'+xmlstring);
      // xmlstring=xmlstring.Substring(1,xmlstring.length());
       //outxmlstring=xmlstring;
       xmlDOC.load(xmlstring); 
       DOM.XMLNode rootElement = xmlDOC.getRootElement();
       outxmlstring=String.valueof(xmlDOC.getRootElement().getName());//gives you root element Name
       for(DOM.XMLNode xmlnodeobj:xmlDOC.getRootElement().getChildElements()){ //gives you all childnodes list
          if(xmlnodeobj.getName()=='Name')
            outxmlstring+='\nAccount Name:'+xmlnodeobj.getText();// it gives you text node
          if(xmlnodeobj.getName()=='Type')
            outxmlstring+='\nAccount Type:'+xmlnodeobj.getText();  
          if(xmlnodeobj.getName()=='Industry')
            outxmlstring+='\nAccount Industry:'+xmlnodeobj.getText();
       }
       
      return null;
    }
}
Vpage:
======
<apex:page controller="Xmlparsercls" sidebar="false">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Parse Xml" action="{!Parsexml}"/>    
                <apex:commandButton value="ParseXML File" action="{!Parsexmlfile}"/>
            </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:outputLabel value="Select Xml File" for="file"/>
            <apex:inputFile fileName="{!fileName}" value="{!body}"/>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Here i am choosing XML format in Text area or in xml file as shown below .According to the file we need to write and parse.

XML format:
===========
<Account>
   <Name>Balaji</Name>
   <Type>Customer</Type>
   <Industry>It</Industry>
</Account>

when you work with this example and want to test with xml file copy the same xml format as above into your notepad and save with ".xml" extension.


Ouput:
=====
When you are selecting file then click on ParseXML file button.
When you type as shown above in the textarea then click on "Parse Xml" button then you can parse the xml.


4 comments:

  1. how to write test class for dom.xmlnode can u please share test class for that

    ReplyDelete
    Replies
    1. Hi Jyoti ,

      we don't need to write test class for dom.xmlnode seperately. Here the functionality is parsing the xml string or xml file. So you have to give input either xml string or xml file.

      Delete

What’s the difference between Einstein Article Recommendations and Suggested Articles?

How Does Einstein Article Recommendations Work? Einstein Article Recommendations helps support agents resolve customer cases efficiently by ...