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

In line 1 I define my Attachment object. In line 3-6 I define some key values.

Line 3 I define the the name o f the file. In this case its PRODUCT_INFO.xml.

Line 4 I grab the value of the XML content I created in Generating an XML file in Apex. I use this value to defined the body of the attachment I have created.

Line 5 I define my content type.

Line 6 I provide the Salesforce ID of the object I want to attach this file to.

Last, line 9, I attempt to insert this file to the object defined in line 6.

The result is that the file will be created as an attachment to the object I specified. On the object there will be a related list for attachments where the xml file can be found.