Monday, November 14, 2011

Read XML AND Insert Data In to Salesforce using apex Code

Hi guys ,
Below is the sample code which let you know how to insert data in Salesforce using XML File.
I am just trying to insert Lead Records in SF.


public class XmlStreamReaderDemo {
    public class Book {
     String name;
     String author;
   }
public List<Book> listRecords = new List<Book>();
  
 public  Book[] parseBooks(XmlStreamReader reader) {
     Book[] books = new Book[0];    
     while(reader.hasNext()) { 
        //  Start at the beginning of the book and make sure that it is a book   
         if (reader.getEventType() == XmlTag.START_ELEMENT) {
            if ('Book' == reader.getLocalName()) {              
                Book book = parseBook(reader);                                //  Pass the book to the parseBook method (below)     
                books.add(book);
            }
         }
        reader.next();
     }
    return books;
   }

  

   public Book parseBook(XmlStreamReader reader) {
    Book book = new Book();
     book.author = reader.getAttributeValue(null, 'author');
     while(reader.hasNext()) {
        if (reader.getEventType() == XmlTag.END_ELEMENT) {
           break;
        } else if (reader.getEventType() == XmlTag.CHARACTERS) {
           //book.name = reader.getText();
           book.name = getDecodedString(reader);
        }
        reader.next();
     }
     return book;
   }

  
   public XmlStreamReaderDemo(string data){
        XmlStreamReader xsr = new XmlStreamReader(data);
        listRecords = parseBooks(xsr);
    }
   
    public void testBookParser() {
     String str = '<books><book author="Chatty">Foo bar</book>' +
        '<book author="Sassy">Baz</book></books>';
     XmlStreamReaderDemo callxml1 = new XmlStreamReaderDemo(str);
     system.debug('callxml1 callxml1 :'+callxml1);
     List<Lead> leadtoInsert = new List<Lead>();
     for(XmlStreamReaderDemo.Book b : callxml1.listRecords) {           
           Lead Ld = new Lead();
           ld.Company = 'x';
           ld.LastName = b.name;
           leadtoInsert.add(ld);         
        }
        system.debug('*********** ::: '+leadtoInsert.size());
        system.debug('*********** ::: '+leadtoInsert);
        if(leadtoInsert.size() >0){
       insert leadtoInsert;
   }
   }
  
     String getDecodedString(Xmlstreamreader reader)
      {
        return EncodingUtil.urlDecode(reader.getText(), 'UTF-8').trim();
      }
}

Use Anonymous Block to execute this code :

XmlStreamReaderDemo  obj = new XmlStreamReaderDemo ( '<books><book author="Chatty">Foo bar</book>' +
        '<book author="Sassy">Baz</book></books>');
obj.testBookParser();

Now you will see two Lead records have been inserted.

Thanks
vijay

3 comments:

  1. Hi
    thanks for this impresssive code and it runs well as a apex code in our account.

    But can u explain me that how u link this code (where u have mention about the url) with a xml so it get data from other xml file like ecommerce sites.

    and can u explain me one thing that i hv read somewhere that if we hv a apex domparser then only we can generate this xml file.

    so please tell me about this so i can configure it properly.

    ReplyDelete
  2. hi Vijay, I'm trying to use your impressive code example to loop through a RSS feed. Could you please explain How I could loop through a list of items (books) that have multiple attributes?
    ABC123>ItemABCABCDEFGABCDEFGHIJKLMNOPQRSTUVWXYZ

    ReplyDelete
    Replies
    1. I am unable to understand string you mentioned here but you can traverse items with multiple attribute with help of getEventType() method which will return you the type of the string if this string is type of Attribute you can perform action based on attribute.If you will see at line 31 XmlTag.CHARACTERS just replace the CHARACTER and use ATTRIBUTE and if this element is type of Attribute traverse you function recursively.
      Here are references
      http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_System_XmlStreamReader_getEventType.htm
      http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_System_XmlStreamReader_instance_methods.htm

      Delete