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