Speeding up XML parsing in Salesforce

When making integrations, it is common to needing to parse XML as external application’s API’s almost always return XML (Web Services or REST).

Before Salesforce’s Spring ’10 edition, XML parsing wasn’t built into the platform, and we used Ron Hess’ XMLDom classes. There was a distinct disadvantage to this library because parsing a large XML document could result in the number of script statements (200,000 per request) being exceeded.

In Spring ’10, there is a new XML stream parser, and because it’s built-in, the class methods do not count towards your script statements used. Now, the XMLStreamReader class doesn’t even closely match the XMLDom class signature, but in the Salesforce developer newsletter there was mention of a Fast XML library by TechGerm.

The new wrapper library was easy to migrate to, and even though the initial test results actually increased the script statements, a quick conversation with the author soon fixed that!

Source code will be posted here soon.

Thanks again go to TechGerm for creating this wrapper library, if you currently have a Salesforce application which uses XMLDom, it’s the fastest way to migrate it and reduce script statements used.

One thought on “Speeding up XML parsing in Salesforce

  1. Vagish Dwivedi says:

    Source Code is as below:

    public class XmlStreamReaderDemo {

    // Create a class Book for processing 

    public class Book {
    String name;
    String author;

    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()) {

    // Pass the book to the parseBook method (below)  

    Book book = parseBook(reader);
    return books;

    // Parse through the XML, deterimine the auther and the characters 

    Book parseBook(XmlStreamReader reader) {
    Book book = new Book();
    book.author = reader.getAttributeValue(null, ‘author’);
    while(reader.hasNext()) {
    if (reader.getEventType() == XmlTag.END_ELEMENT) {
    } else if (reader.getEventType() == XmlTag.CHARACTERS) {
    book.name = reader.getText();
    return book;

    // Test that the XML string contains specific values 

    static testMethod void testBookParser() {

    XmlStreamReaderDemo demo = new XmlStreamReaderDemo();

    String str = ‘Foo bar’ +

    XmlStreamReader reader = new XmlStreamReader(str);
    Book[] books = demo.parseBooks(reader);


    for (Book book : books) {

Leave a Reply

Your email address will not be published. Required fields are marked *