function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
giri rockzzzzgiri rockzzzz 

how to write xml in apex class??

i want to fill all account names in xml......how to write in xml ????

any one help..

sfdcfoxsfdcfox

You use the XmlStreamWriter to create XML easily. You may do something like the following:

 

 

XmlStreamWriter w = new XmlStreamWriter();
w.writeStartDocument(null,'1.0');
w.writeStartElement(null,'account',null);
for(account a:[select id,name from account])
{
  w.writeStartElement(null,'id',null);
  w.writeCharacters(String.valueOf(a.id));
  w.writeEndElement();
  w.writeStartElement(null,'name',null);
  w.writeCharacters(a.name);
  w.writeEndElement();
}
w.writeEndElement();
w.writeEndDocument();
string xml = w.getXmlString();
w.close();
return xml;

 The specific format depends on your DTD and so on, but this is the basic information. Please check http://www.salesforce.com/us/developer/docs/apexcode/salesforce_apex_language_reference.pdf for more information.

 

Adil_SFDCAdil_SFDC

what would the output of above looks like

sfdcfoxsfdcfox

I actually tested this code, and found out I made a mistake. Here's my revised code:

 

XmlStreamWriter w = new XmlStreamWriter();
w.writeStartDocument(null,'1.0');
w.writeStartElement(null,'accounts',null);
for(account a:[select id,name from account])
{
  w.writeStartElement(null,'account',null);
  w.writeStartElement(null,'id',null);
  w.writeCharacters(String.valueOf(a.id));
  w.writeEndElement();
  w.writeStartElement(null,'name',null);
  w.writeCharacters(a.name);
  w.writeEndElement();
  w.writeEndElement();
}
w.writeEndElement();
w.writeEndDocument();
string xml = w.getXmlString();
w.close();
system.debug(xml);

Here's an example output:

 

<?xml version="1.0"?><accounts><account><id>0014000000Fytb3AAB</id><name>Reason Foundation</name></account><account><id>0014000000cj0KGAAY</id><name>Fire</name></account></accounts>

As you can see, it's quite easy to generate XML with this stream writer class.

Amegi18Amegi18

Excuse me,, umm,, is that idea also possible with just reading/processing the xml tags?

Like what if I don't need to get any data from xml but would want the xml tags to be recognized?

 

Like this code for example: 

 - how would it look like if written in apex ?

 

    <xml>
     <x:ExcelWorkbook>
      <x:ExcelWorksheets>
       <x:ExcelWorksheet>
        <x:Name>Trial</x:Name>
        <x:WorksheetOptions>
         <x:Zoom>80</x:Zoom>
         <x:FitToPage/> 
         <x:Print> 
          <x:FitWidth>1</x:FitWidth> 
          <x:FitHeight>1000</x:FitHeight> 
          <x:ValidPrinterInfo/> 
         </x:Print> 
        </x:WorksheetOptions>
       </x:ExcelWorksheet>
      </x:ExcelWorksheets>
     </x:ExcelWorkbook>
    </xml>