Wednesday, May 07, 2014

Why we need to use XmlStreamWriter?

Sometimes we [maybe only me] choose the simple method to achieve something.Well, if the objective is done, what else we need to think.

Actually I just want to write about XMLStreamWriter.Some code that I reviewed using simple method to generate XML, which is by appending the string.Well thinking that I going to be safe,I just proceed appending the string like example below.
Example
 String xmlStr ='<user xmlns:i="http://www.w3.org/2001/XMLSchema-instance">';
  if(displayName!=null)
  xmlStr+='<displayname>'+displayName+'</displayname>';
  if(Group!=null)
  xmlStr+='<group>'+groupName+'</group>';
  xmlStr+='</user>';
It goes well after quite some time until one day ,a user shout out about an error. 500 : There was an error deserializing the object of type bla bla.. Whenever a programmer face error, we will google it =) .I notice there & symbol in the data and it caused the issue.So the proper way to write xml is by using XmlStreamWriter.
XmlStreamWriter  w= new XmlStreamWriter();
 w.writeStartElement(null, 'User',null );
 w.writeNamespace('i','http://unid-machine.blogspot.com');
 w.writeStartElement(null,'DisplayName',null);
 w.writeCharacters('Unid');
 w.writeEndElement();
        w.writeStartElement(null,'Groups',null);
        w.writeStartElement(null,'Group',null);
        w.writeCharacters('Group1');
        w.writeEndElement();
        w.writeStartElement(null,'Group',null);
        w.writeCharacters('Group2');
        w.writeEndElement();
        w.writeEndElement(); //groups
 w.writeEndElement();
 
        system.debug('@Xml string '+ w.getXmlString());
Okay, bring it on user whatever data you like =) . The example of output
<user xmlns:i="http://unid-machine.blogspot.com">
<displayname>Unid</displayname>
<groups>
<group>Group1</group>
<group>Group2</group>
</groups>
</user>
Reference:XmlStreamWriter

No comments:

Post a Comment