Attachment To Object in Apex

In an earlier post, Generating an XML file in Apex, we created an XML document Xmlstreamwriter class. This post we will take the XML and attach it to an object. The code to do so is pretty straight forward:

1  Attachment attachmentProductInfo = new Attachment(); 
2  
3  attachmentProductInfo.Name = 'PRODUCT_INFO.xml';
4  attachmentProductInfo.Body = Blob.valueOf(xmlFinalProductList); 
5  attachmentProductInfo.ContentType = 'application/xml';
6  attachmentProductInfo.ParentID='OBJECT_ID';
7
8  try{
9   insert attachmentProductInfo; 
10   }catch (DmlException e) {
11  System.debug('The following exception has occurred: ' + e.getMessage());
12   return e.getMessage();
13  }

Generating an XML File in Apex

I recently had the task to create some XML files based on object data and create an attachment. I’ve created XML files before in say Ruby and PHP but not in Apex. This was new to me and in the end was an easier task than I thought it would be.

First let’s create an objective. We want to create an XML file that has the following format:

1  <?XML encoding="utf-8" version="1.0" ?>
2  <catalog>
3   <product id="bk101">
4      <author>Mix Master Mike</author>
5      <title>XML In Apex</title>
6      <genre>Salesforce</genre>
7      <price>1444.95</price>
8      <publish_date>20016-12-10</publish_date>
9      <description>An in-depth look at creating applications with XML.</description>
10   </product>
11 </catalog>

This seems simple enough.