function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SurjenduSurjendu 

XML Parsing...Help solicited

I have the following XML
<project-entities>
 <response>
<users>
    <user>
         <user-id>testthree</user-id>
         <code>Failure</code>
        <desc>User with the same email address exists</desc>
    </user>
    <user>
        <user-id>testtwo</user-id>
        <code>Failure</code>
        <desc>User with the same email address exists</desc>
    </user>
 </users>
</response>
</project-entities>


How do I parse the xml to get corresponding value for userid,code,desc etc

I know i can use XMLStreamReader class but I just cant able to figure out how to parse to get the mapping (such as user-id testthree  has a code of failure). I can parse the whole tree but how do I make sure that a particular user block is parsed correctly. I need to parse the tree and create separate User objects.

public void parseResponse(XmlStreamReader reader)
{
while(reader.hasNext())
{
if(reader.getEventType() == XmlTag.START_ELEMENT)
{

}

if(reader.getEventType() == XmlTag.CHARACTERS)
{
System.debug('Text :::' + reader.getText());
}
reader.next();
}
}

Ron HessRon Hess
here is my simplistic effort at parsing a nested object inside an XML response, take a look and see if you can modify it to meet your needs.

I've not yet come up with a truly object oriented (gereralized) version of this, so if you have one please share it.


Code:
  while(reader.hasNext()) { 
   if(debug >3) system.debug( 'parseACLResponse '+reader.getEventType() + reader.getLocalName()  );
   
   //if (reader.isEndElement())  break;
   
   if (reader.isStartElement() ) {
    string n = reader.getLocalName();
     
      if (n=='AccessControlPolicy') {
       acp.owner = getValue(reader,'ID'); // assumes the order of elements
       acp.displayName= getValue(reader,'DisplayName');
      }
      
      if (n=='Grantee') {
       Grant g = new grant(); 
       g.owner = getValue(reader,'ID'); // assumes the order of elements
       g.displayName= getValue(reader,'DisplayName');
       g.permission = getValue(reader,'Permission');
       acp.grants.add(g);
      }
      
   }
   reader.next();
  }

    string getValue(XmlStreamReader reader, string sn) { 
  String value; 
      while(reader.hasNext()) {
       if (debug > 2) system.debug( 'getValue2 '+reader.getEventType() + reader.getLocalName()  );
         if (reader.isEndElement() && reader.getLocalName() == sn) 
          break;
         if (reader.isCharacters() ) { 
          value = reader.getText();
         }
         reader.next();
      } return value;
    }

 

Ad_InfosysAd_Infosys

If I have a large XML from other external application.

I have the XML on the server i.e. my local machine. the location is something like

C:\\Documents and Settings\\rahul_arora\\Desktop\\book.xml

Now I want this to be utilised in SFDC. All the examples to read the XML have the XML code converted to string and then instantiate the XMLStreamReader.

How do I do in my case. Kindly suggest the elaborated approach.

cheenathcheenath
Apex is executed on sfdc servers. You wont be able to read
the xml file in your desktop from apex.


Ad_InfosysAd_Infosys

Thanks Dear...

SO Will it work in a way if I copy the code in the XML file and place it in first line inside quotes...

String xmlString = 'Paste XML content';

XmlStreamReader xsr = new XmlStreamReader(xmlString);

...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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;
    }
}