XmlStreamReader Class

Similar to the XMLStreamReader utility class from StAX, methods in the XmlStreamReader class enable forward, read-only access to XML data. You can pull data from XML or skip unwanted events.

The following code snippet illustrates how to instantiate a new XmlStreamReader object:
String xmlString = '<books><book>My Book</book><book>Your Book</book></books>';
XmlStreamReader xsr = new XmlStreamReader(xmlString);

These methods work on the following XML events:

Use the next and hasNext methods to iterate over XML data. Access data in XML using get methods such as the getNamespace method.

Note
The XmlStreamReader class in Apex is based on its counterpart in Java. See java.xml.stream.XMLStreamReader.

The following methods are available to support reading XML files:

Name Arguments Return Type Description
getAttributeCount Integer Returns the number of attributes on the start element. This method is only valid on a start element or attribute XML events. This value excludes namespace definitions. The count for the number of attributes for an attribute XML event starts with zero.
getAttributeLocalName Integer index String Returns the local name of the attribute at the specified index. If there is no name, an empty string is returned. This method is only valid with start element or attribute XML events.
getAttributeNamespace Integer index String Returns the namespace URI of the attribute at the specified index. If no namespace is specified, null is returned. This method is only valid with start element or attribute XML events.
getAttributePrefix Integer index String Returns the prefix of this attribute at the specified index. If no prefix is specified, null is returned. This method is only valid with start element or attribute XML events.
getAttributeType Integer index String Returns the XML type of the attribute at the specified index. For example, id is an attribute type. This method is only valid with start element or attribute XML events.
getAttributeValue String namespaceURI

String localName

String Returns the value of the attribute in the specified localName at the specified URI. Returns null if the value is not found. You must specify a value for localName. This method is only valid with start element or attribute XML events.
getAttributeValueAt Integer index String Returns the value of the attribute at the specified index. This method is only valid with start element or attribute XML events.
getEventType System.XmlTag XmlTag is an enumeration of constants indicating the type of XML event the cursor is pointing to:
  • ATTRIBUTE
  • CDATA
  • CHARACTERS
  • COMMENT
  • DTD
  • END_DOCUMENT
  • END_ELEMENT
  • ENTITY_DECLARATION
  • ENTITY_REFERENCE
  • NAMESPACE
  • NOTATION_DECLARATION
  • PROCESSING_INSTRUCTION
  • SPACE
  • START_DOCUMENT
  • START_ELEMENT
getLocalName String Returns the local name of the current event. For start element or end element XML events, it returns the local name of the current element. For the entity reference XML event, it returns the entity name. The current XML event must be start element, end element, or entity reference.
getLocation String Return the current location of the cursor. If the location is unknown, returns -1. The location information is only valid until the next method is called.
getNamespace String If the current event is a start element or end element, this method returns the URI of the prefix or the default namespace. Returns null if the XML event does not have a prefix.
getNamespaceCount Integer Returns the number of namespaces declared on a start element or end element. This method is only valid on a start element, end element, or namespace XML event.
getNamespacePrefix Integer index String Returns the prefix for the namespace declared at the index. Returns null if this is the default namespace declaration. This method is only valid on a start element, end element, or namespace XML event.
getNamespaceURI String Prefix String Return the URI for the given prefix. The returned URI depends on the current state of the processor.
getNamespaceURIAt Integer Index String Returns the URI for the namespace declared at the index. This method is only valid on a start element, end element, or namespace XML event.
getPIData String Returns the data section of a processing instruction.
getPITarget String Returns the target section of a processing instruction.
getPrefix String Returns the prefix of the current XML event or null if the event does not have a prefix.
getText String Returns the current value of the XML event as a string. The valid values for the different events are:
  • The string value of a character XML event
  • The string value of a comment
  • The replacement value for an entity reference. For example, assume getText reads the following XML snippet:
    <!ENTITY
      Title "Salesforce For Dummies" >
         ]>
      <foo a=\"b\">Name &Title;</foo>';
    The getText method returns Salesforce for Dummies, not &Title.
  • The string value of a CDATA section
  • The string value for a space XML event
  • The string value of the internal subset of the DTD
getVersion String Returns the XML version specified on the XML declaration. Returns null if none was declared.
hasName Boolean Returns true if the current XML event has a name. Returns false otherwise. This method is only valid for start element and stop element XML events.
hasNext Boolean Returns true if there are more XML events and false if there are no more XML events. This method returns false if the current XML event is end document.
hasText Boolean Returns true if the current event has text, false otherwise The following XML events have text: characters, entity reference, comment and space.
isCharacters Boolean Returns true if the cursor points to a character data XML event. Otherwise, returns false.
isEndElement Boolean Returns true if the cursor points to an end tag. Otherwise, it returns false.
isStartElement Boolean Returns true if the cursor points to a start tag. Otherwise, it returns false.
isWhiteSpace Boolean Returns true if the cursor points to a character data XML event that consists of all white space. Otherwise it returns false.
next Integer Reads the next XML event. A processor may return all contiguous character data in a single chunk, or it may split it into several chunks. Returns an integer which indicates the type of event.
nextTag Integer Skips any white space (the isWhiteSpace method returns true), comment, or processing instruction XML events, until a start element or end element is reached. Returns the index for that XML event. This method throws an error if elements other than white space, comments, processing instruction, start elements or stop elements are encountered.
setCoalescing Boolean returnAsSingleBlock Void If you specify true for returnAsSingleBlock, text is returned in a single block, from a start element to the first end element or the next start element, whichever comes first. If you specify it as false, the parser may return text in multiple blocks.
setNamespaceAware Boolean isNamespaceAware Void If you specify true for isNamespaceAware, the parser recognizes namespace. If you specify it as false, the parser does not. The default value is true.
toString String Returns the length of the input XML given to XmlStreamReader.

XmlStreamReader Example

The following example processes an XML string.

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);
                books.add(book);
            }
         }
        reader.next();
     }
    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) {
           break;
        } else if (reader.getEventType() == XmlTag.CHARACTERS) {
           book.name = reader.getText();
        }
        reader.next();
     }
     return book;
   }

// Test that the XML string contains specific values 
    
   static testMethod void testBookParser() {

     XmlStreamReaderDemo demo = new XmlStreamReaderDemo();

     String str = '<books><book author="Chatty">Foo bar</book>' +
        '<book author="Sassy">Baz</book></books>';

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

     System.debug(books.size());

     for (Book book : books) {
       System.debug(book);
     }
   }
}
© Copyright 2000–2012 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.