http://salesforceapexcodecorner.blogspot.com
http://blogs.developerforce.com
http://it.toolbox.com/
Some of it using XMLStreamReader and some using XMLNode.But I choose to use XMLStreamReader.Why? I think it enough for my project requirement and for this time being I am
able to understand XMLStreamReader better.
If you refer to links above, most of it giving simple XML which only contain one element.During my self study, I am trying to read XML file whereby the element contains sub elements such as below
<user xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <id>2262</id> <displayname>Unidha</displayname> <email>unidha@yahoo.com</email> <usergroups> <usergroup><id>301</id><name>Administrators</name></usergroup> <usergroup><id>302</id><name>Sales</name></usergroup> </usergroups> <city>Cybercity</city></user>
public class MyXmlStreamReader { //object that hold information on transaction,user etc. class Employee{ private List<String> GroupId{get;set;} //one user might have multiple group being assigned private Boolean autoProvision{get;set;} private Id userId{get;set;} private String email{get;set;} private String displayName{get;set;} private String city{get;set;} } public void test() { String str = '<user xmlns:i="http://www.w3.org/2001/XMLSchema-instance">' +'<id>2262</id>' +'<displayname>Unidha</displayname>' +'<email>unidha@yahoo.com</email>' +'<usergroups>' +'<usergroup><id>301</id><name>Administrators</name></usergroup>' +'<usergroup><id>302</id><name>Sales</name></usergroup>' +'</usergroups>' +'<city>Cybercity</city></user>'; XmlStreamReader xsr = new XmlStreamReader(str); readResponse(xsr); } public void readResponse(XmlStreamReader reader) { boolean isFlag=false; Employee empRecord= new Employee (); empRecord.GroupId=new List<String>(); while (reader.hasNext()) { if (reader.getEventType() == XmlTag.START_ELEMENT) { if ('Id' == reader.getLocalName()) { String strId= getValueFromTag(reader); if(isFlag){ empRecord.GroupId.add(strId); } } else if ('DisplayName' == reader.getLocalName()) { empRecord.displayName= getValueFromTag(reader); } else if ('Email' == reader.getLocalName()) { empRecord.email= getValueFromTag(reader); } else if('UserGroups' == reader.getLocalName()) { isFlag=true; } else if('City' == reader.getLocalName()) { empRecord.city= getValueFromTag(reader); } } else if (reader.getEventType() == XmlTag.END_ELEMENT){ if('UserGroups' == reader.getLocalName()){ isFlag=false; } } reader.next(); }//end of while } }//end of class
That's it.My problem is solved for this time being.Let's drink some coffeee with cinnamon roll.Yum yum!
No comments:
Post a Comment