Screaming for XMLStreamReader!!

I am studying on how to extract data from xml file.Actually I need to learn it for my project requirement.So I googling around and found these nice links.

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="">
 <usergroup><id>301</id><name>Administrators</name></usergroup> <usergroup><id>302</id><name>Sales</name></usergroup>
Notice that beside <Id>2262</Id> ,there Id for UserGroups which are 301 and 302.Now I am going to read the Id without get confuse which one is User id and which one is Group Id.The code below is wrote based on article in link I mentioned above.
public class MyXmlStreamReader {

   //object that hold information on transaction,user etc.
     class Employee{
        private List&lt;String&gt; 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="">'

     XmlStreamReader xsr = new XmlStreamReader(str);

   public void readResponse(XmlStreamReader reader) {
    boolean isFlag=false;
    Employee   empRecord= new Employee ();
    empRecord.GroupId=new List&lt;String&gt;();
   while (reader.hasNext()) { 
        if (reader.getEventType() == XmlTag.START_ELEMENT) { 
           if ('Id' == reader.getLocalName()) {
              String strId= getValueFromTag(reader);
            else if ('DisplayName' == reader.getLocalName()) {
                empRecord.displayName= getValueFromTag(reader);
             else if ('Email' == reader.getLocalName()) {
           else if('UserGroups' == reader.getLocalName()) {
            else if('City' == reader.getLocalName()) {
          else if (reader.getEventType() == XmlTag.END_ELEMENT){
             if('UserGroups' == reader.getLocalName()){
            }//end of while
      }//end of class
Now, watch closely at isFlag variable.I use this boolean to indicate when the Id is UserId and when it is become the GroupId.

That's it.My problem is solved for this time being.Let's drink some coffeee with cinnamon roll.Yum yum!


Popular Posts