Newer Version Available

This content describes an older version of this product. View Latest

Writing XML Using Streams

The XmlStreamWriter class methods enable the writing of XML data.
Those methods are used in conjunction with HTTP callouts to construct an XML document to send in the callout request to an external service. The following example shows how to instantiate a new XmlStreamReader object:
1String xmlString = '<books><book>My Book</book><book>Your Book</book></books>';
2XmlStreamReader xsr = new XmlStreamReader(xmlString);

XML Writer Methods Example

The following example writes an XML document and tests its validity.

The Hello World and the shipping invoice samples require custom fields and objects. You can either create these on your own, or download the objects, fields and Apex code as a managed packaged from Force.com AppExchange. For more information, see https://developer.salesforce.com/docs.

Note

1swfobject.registerObject("clippy.codeblock-1", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class XmlWriterDemo {
18
19     public String getXml() {
20          XmlStreamWriter w = new XmlStreamWriter();
21          w.writeStartDocument(null, '1.0');
22          w.writeProcessingInstruction('target', 'data');
23          w.writeStartElement('m', 'Library', 'http://www.book.com');
24          w.writeNamespace('m', 'http://www.book.com');
25          w.writeComment('Book starts here');
26          w.setDefaultNamespace('http://www.defns.com');
27          w.writeCData('<Cdata> I like CData </Cdata>');
28          w.writeStartElement(null, 'book', null);
29          w.writedefaultNamespace('http://www.defns.com');
30          w.writeAttribute(null, null, 'author', 'Manoj');
31          w.writeCharacters('This is my book');
32          w.writeEndElement(); //end book
33          w.writeEmptyElement(null, 'ISBN', null);
34          w.writeEndElement(); //end library
35          w.writeEndDocument();
36          String xmlOutput = w.getXmlString();
37          w.close();
38          return xmlOutput;
39        }
40}
1swfobject.registerObject("clippy.codeblock-2", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17@isTest
18private class XmlWriterDemoTest {
19    static TestMethod void basicTest() {
20        XmlWriterDemo demo = new XmlWriterDemo();
21        String result = demo.getXml();
22        String expected = '<?xml version="1.0"?><?target data?>' +
23            '<m:Library xmlns:m="http://www.book.com">' + 
24            '<!--Book starts here-->' +
25            '<![CDATA[<Cdata> I like CData </Cdata>]]>' +
26'<book xmlns="http://www.defns.com" author="Manoj">This is my book</book><ISBN/></m:Library>';
27        
28        System.assert(result == expected);
29    }
30}