+ Start a Discussion
venkateshvenkatesh 

XML parsing!!!

Hi ,

 m nt getting proper xml parsing method info ..

I have this XML :-

 

<customers>
  <PID AD_Table_ID="291" Record_ID="117">
     <AD_Client_ID>11</AD_Client_ID>
     <AD_Language/>
     <AD_OrgBP_ID/>
     <AD_Org_ID>0</AD_Org_ID>
     <AcqusitionCost>0</AcqusitionCost>

  </PID>

  <PID AD_Table_ID="291" Record_ID="113">
     <AD_Client_ID>12</AD_Client_ID>
     <AD_Language/>
     <AD_OrgBP_ID/>
     <AD_Org_ID>0</AD_Org_ID>
     <AcqusitionCost>0</AcqusitionCost>

   </PID>

 

 </customers>

 

m tryin to parse it since a day ...i saw the methods and example in the apex reference and some samples also..But i am not getting the method by which i can travse through this tree structure.. XML parsing is much easier in java , but as m using SFDC IDE , no auto fill is thr ..its a bit hard for me to debug and find out the methods i need..it will be so kind if any one can give me some clue (i went through the XmlStreamReader some properties)..thnx

Best Answer chosen by Admin (Salesforce Developers) 
Scott.MScott.M

I like to use googles XMLDom class for parsing xml requests. It's simple and it works pretty well. It's included in the google data toolkit for salesforce. You can just pull out the XMLDom and XMLDomTest classes since they don't depend on any other classes. Just thought I'd mention it :) 

All Answers

SuperfellSuperfell
http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_classes_XmlStream_reader.htm
venkateshvenkatesh

SImon ..thnx for that quick reply..i got that link from one of your previous posts..please rectify if i made any mistakes :-

 

public static void parseAccounts(XmlStreamReader reader){
    Account[] accs = new Account[0];
    while(reader.hasNext()) {
   
         if (reader.getEventType() == XmlTag.START_ELEMENT) {
            if ('C_BPartner' == reader.getLocalName()) {
                accs.add(parseAccount(reader));
            }
         }
        reader.next();
       
     }
    
     for(Account a:accs){
         a.hello__c = 'Smruti Inserts'; <----------- i have 9 nodes all different but when m insterting it inserts the 1st node 9 times?? So i would like to know if i hv some mistakes in inserting or traversing..

        insert a;
     }

}

   public static Account parseAccount(XmlStreamReader reader) {
     Account acc = new Account();
     while(reader.hasNext()) {
        if (reader.getEventType() == XmlTag.END_ELEMENT) {
           break;
        } else if (reader.getEventType() == XmlTag.CHARACTERS) {
           acc.name = reader.getText();
           acc.Custom_Account_Id__c = reader.getText();          
        }
        reader.next();
     }
     return acc;
   }

 

Note : please rectify if any mistakes..thnx

venkateshvenkatesh

k its working now..thnx :D ...but still m not getting what i want..

i.e traversing through the all recors..m getting only the 1st records Id value..

 

by reader.getText() <--- it gives only the 1st element value from the above mentioned XML...How do i suppose to get/traverse through my all values...

 

like <id></id>

       <name></name>

       <date></date>...

 

when i do getText() by reaching that node --> it gives me id value only the 1st element value...i need the name and date for the same node?? thnx

SuperfellSuperfell
you have to move the reader onto the next set of elements. this is a standard pull parser style api, there should be plenty of tutorials available.
venkateshvenkatesh

ok thnx Simon..m gonna do a R 'n' D on that , then will comeback..thnx for ur valuable time and quick responses :)

Message Edited by venkatesh on 02-22-2009 10:44 PM
Scott.MScott.M

I like to use googles XMLDom class for parsing xml requests. It's simple and it works pretty well. It's included in the google data toolkit for salesforce. You can just pull out the XMLDom and XMLDomTest classes since they don't depend on any other classes. Just thought I'd mention it :) 

This was selected as the best answer
venkateshvenkatesh

Oh yeah i was just looking at that code since 24 hrs..its just awesome , btw thnx Scotty..

 

and thnx ron H. for that nice bit of code :D

Ramakrishnan AyyanarRamakrishnan Ayyanar
I created one simple XML Parsing.I have Used one VF page and Apex Class.It's parsing correctly ...

VF Page:

<apex:page Controller="Xmlparsar">

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

Apex Class:

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())
       {        
         
         
          loadChilds(xmlnodeobj);         
       }      
       return null;
    }
   
    //loading the child elements
    private void loadChilds(DOM.XMLNode xmlnode)
    {
        for(Dom.XMLNode child : xmlnode.getChildElements())
        {
          if(child.getText()!= null)
          {
          outxmlstring+='\n'+child.getName()+': '+child.getText();
       
          }
          loadChilds(child);       
        }
    }
   
   
//This is for parsing xml file what you selected
  public pagereference Parsexmlfile()
  {
       DOM.Document xmlDOC = new DOM.Document();
       xmlstring=body.tostring();         
       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())
       {        
                  
          loadChilds(xmlnodeobj); 
       }      
      return null;
    }
}