0

How to generated the below XMl Based on list size?

Hi,

the below list has 3 records. I need to generate the below XML Structure Based on list size.

List<Product_for_Sample_Literature__c>  ProductLineItems =[SELECT id,Sample_Literature_Request__c,Batch_Information__c,Detail__c,Product__r.Name,Quantity__c,Product_APN__c  from Product_for_Sample_Literature__c WHERE Sample_Literature_Request__c ='a0Eb0000001UVLF'];

If list size has one, the XMl should like this.And assign the values of list to below elements

<Items>
            <SFDCLineID>1</SFDCLineID>
            <Material>ProductLineItems.Batch_Information__c</Material>
            <Quantity>ProductLineItemsQuantity__c</Quantity>

</Items>

If list size has two, the XMl should like this.

<Items>
            <SFDCLineID>1</SFDCLineID>
            <Material>ProductLineItems.Batch_Information__c</Material>
            <Quantity>ProductLineItemsQuantity__c</Quantity>

</Items>

<Items>
            <SFDCLineID>2</SFDCLineID>
            <Material>ProductLineItems.Batch_Information__c</Material>
            <Quantity>ProductLineItemsQuantity__c</Quantity>

</Items>

the list size has 3 ,

<Items>
            <SFDCLineID>1</SFDCLineID>
            <Material>ProductLineItems.Batch_Information__c</Material>
            <Quantity>ProductLineItemsQuantity__c</Quantity>

</Items>

<Items>
            <SFDCLineID>2</SFDCLineID>
            <Material>ProductLineItems.Batch_Information__c</Material>
            <Quantity>ProductLineItemsQuantity__c</Quantity>

</Items>

<Items>
            <SFDCLineID>3</SFDCLineID>
            <Material>ProductLineItems.Batch_Information__c</Material>
            <Quantity>ProductLineItemsQuantity__c</Quantity>

</Items>

etc, how i can acheive this ?can anyone help me on this

  • Have you tried something? Do you have an idea how to achieve it? Are you blocked with something? Or do you want community to write your code instead you? :) – Oleksandr Berehovskyi Nov 22 '17 at 11:04
  • i don't have any idea how to achieve this. – Spyder Nov 22 '17 at 11:10
  • no worries ! there is a nice example that will help you to understand how you can do it with apex. – Oleksandr Berehovskyi Nov 22 '17 at 11:13
3

Try with this

Apex provides classes that enable you to work with XML content using the DOM (Document Object Model).

Execute below code in anonymous window,

List<Product_for_Sample_Literature__c>  ProductLineItems =[SELECT id,Sample_Literature_Request__c,Batch_Information__c,Detail__c,Product__r.Name,Quantity__c,Product_APN__c  from Product_for_Sample_Literature__c WHERE Sample_Literature_Request__c ='a0Eb0000001UVLF'];

    Dom.Document doc = new Dom.Document();    
    Dom.Xmlnode rootNode = doc.createRootElement('ProductLineItems', null, null);        
    Integer SFDCLineID=0;

    for (Product_for_Sample_Literature__c Product: ProductLineItems ) {
        Dom.Xmlnode ProductNode = rootNode.addChildElement('Items', null, null);
        ProductNode.addChildElement('SFDCLineID', null, null).addTextNode(++SFDCLineID);
        ProductNode.addChildElement('Material', null, null).addTextNode(Product.Batch_Information__c);
        ProductNode.addChildElement('Quantity', null, null).addTextNode(Product.Quantity__c);

    }        
    system.debug(doc.toXmlString());  

Resulting log, you will be getting the XML String like below

<?xml version="1.0" encoding="UTF-8"?>
<ProductLineItems>
<Items>
            <SFDCLineID>1</SFDCLineID>
            <Material>Product 1</Material>
            <Quantity>3</Quantity>

</Items>
<Items>
            <SFDCLineID>2</SFDCLineID>
            <Material>Product 2</Material>
            <Quantity>4</Quantity>

</Items>
</ProductLineItems>
|improve this answer|||||
  • System.NullPointerException: Argument 1 cannot be null – Spyder Nov 22 '17 at 12:38
  • I am getting the above error when i am trying to execute the above code in anonymous window, – Spyder Nov 22 '17 at 12:39
  • Value your receiving from "Product_for_Sample_Literature__c" object , Has null values, because of that your getting error. – NITHESH K Nov 22 '17 at 12:41
  • @Spyder Below code is tested with account, as i dont have your object in my org. Dom.Document doc = new Dom.Document(); Dom.Xmlnode rootNode = doc.createRootElement('ProductLineItems', null, null); list<account> accountList = [select id, name from Account limit 10 ]; for (Account eachAccount : accountList) { Dom.Xmlnode accountNode = rootNode.addChildElement('Account', null, null); accountNode.addChildElement('id', null, null).addTextNode(eachAccount.id); accountNode.addChildElement('Name', null, null).addTextNode(eachAccount.Name); } system.debug(doc.toXmlString()); – NITHESH K Nov 22 '17 at 12:44
  • Its working Nitesh – Spyder Nov 22 '17 at 12:50
0

You can generate XML using the classes in the Dom namespace, but there's an easier way (well, easier for me at least).

You can use Visualforce to generate XML.

<!-- 
    You'll probably need to create a small controller extension.
    showHeader, standardStyleSheets, sidebar, applyBodyTag, and applyHtmlTag are all set
      to false to prevent the HTML that Salesforce usually generates automatically
      from appearing in the XML

-->
<apex:page standardController="Product_for_Sample_Literature__c" extensions="MyExtension" showHeader="false" standardStyleSheets="false" sidebar="false" contentType="text/xml" applyBodyTag="false" applyHtmlTag="false" cache="false">
<!-- I think there's an issue with printing the xml header tag, so we'll need to take care
  of that elsewhere -->
<apex:repeat value="{!records}" var="lineItem">
    <!-- 
    There's no problem using non-visualforce, non-html tags here.
    We don't need to do anything special to make up our own tags (XML is just a bunch of
      arbitrarily defined tags, after all).
    With the contentType being text/xml, your browser won't try to render these
      tags as HTML.
    -->
    <Items>
        <!-- There's no standard way to get the current index number of an apex:repeat.
        There are a few different ways you could achieve this, but I'll leave that 
          for you to figure out.
        -->
        <material>{!lineItem.Batch_Information__c}</material>
        <quantity><!-- the code/merge syntax statement in here will be similar to the one above --></quantity>
    </Items>
</apex:repeat>

The extension class you would need is really straightforward.

public class MyExtension{
    // Variable to hold the records that we need to query
    List<Product_For_Sample_Literature__c> records{get;set;}

    // The same, basic constructor signature for a controller extension
    public MyExtension(ApexPages.StandardController con){
        // Just like if this were for a regular visualforce page, you'll need to query
        //   for all the fields that you'll be using
        // We need to use ApexPages.currentPage() to get the page parameters that you
        //   pass in.
        records = [SELECT Id, Batch_Information__c, Quantity__c FROM Product_For_Sample_Literature__c WHERE Sample_Literature_Request = :ApexPages.currentPage().getParameters().get('reqNum')];
    }
}

Using these to generate XML in Apex is also pretty simple.

PageReference myXMLGenerator = Page.MyVisualforcePage;
myXMLGenerator.getParameters.put('reqNum', 'a0Eb0000001UVLF');
String xmlResult;

if(!Test.isRunningTest()){
    // As of API v34.0, pageReference.getContent() is considered a callout.
    // That means that we can't run this code in a unit test, which is the primary
    //   drawback to this approach.
    xmlResult = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' + myXMLGenerator.getContent().toString());
}

For very short and simple XML structures, like the one in your example, this approach probably involves more code/typing than just using the classes in the Dom namespace. However, for more complicated XML (especially if you have a few levels of nested tags), this approach stands head and shoulders above trying to generate XML with Apex alone.

The other benefit to this approach is that, being a visualforce page, it's pretty simple to just open a tab in your browser, navigate to /apexPages/MyVisualforcePage?reqNum="a0Eb0000001UVLF", and look at the resulting XML to verify that the XML looks correct (no need for anonymous apex and debug statements).

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.