Wednesday, March 29, 2017

Simple way to generate XML, parse and retrieve values from XML

Use Case

We usually get a requirement to store Salesforce records in XML format. Later, we may need to parse the XML and retrieve the data from XML and store them into a Map for future use.

Solution

I have created this class to generate some hard coded data. Later through usable parseXML method that has been parsed.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class XMLParserClass
{
    public Map<String, String> xmlDataMap = new Map<String,String>();
    
    public String generateXML()
    {
        Dom.Document doc = new Dom.Document();
        Dom.Xmlnode rootNode = doc.createRootElement('TestReport', null, null);
        
        Dom.Xmlnode headerNode = rootNode.addChildElement('header', null, null);
        //assign header attributes
        headerNode.setAttribute('id', 'TEST1'); 
        
        Dom.Xmlnode childNode = headerNode.addChildElement('detail', null, null);               
        childNode.setAttribute('id','CHILD1');              
        childNode.setAttribute('Amount','1000');  
        
        String xmlString = doc.toXmlString();
        System.debug('xmlString =' + xmlString);
        return xmlString;
    }
    
 //generated xml
 /*
    <?xml version="1.0" encoding="UTF-8"?>
    <TestReport>
    <header id="TEST1">
    <detail id="CHILD1" Amount="1000" />
    </header>
    </TestReport>
    */
 
 
    public void parserXML(String toParse)
    {
        xmlDataMap = new Map<String,String>();
        DOM.Document doc = new DOM.Document();
        try{
            doc.load(toParse);
            DOM.XMLNode root = doc.getRootElement();
            traverseThroughXML(root);
        }catch(Exception ex){
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, ex.getMessage());
            ApexPages.addMessage(msg);
       }  
    }
    
    /**
     * traverseThroughXML
     * This method traverse through the xml, read the data from XML.
     * @param
     * @return void.
     */
    private void traverseThroughXML(DOM.XMLNode node) 
    {
        if (node.getNodeType() == DOM.XMLNodeType.ELEMENT) 
        {
            System.debug('node.getName()=' + node.getName());
            if(node.getName().equalsIgnoreCase('detail'))
            {
                if (node.getAttributeCount() > 0) 
                { 
                  xmlDataMap.put(node.getAttributeValue(node.getAttributeKeyAt(0), node.getAttributeKeyNsAt(0))
                                ,node.getAttributeValue(node.getAttributeKeyAt(1), node.getAttributeKeyNsAt(1)));
                }
            }
            for (Dom.XMLNode child: node.getChildElements()) 
            {
              traverseThroughXML(child);
            }
        } 
    }
}

Usage

1
2
3
4
XMLParserClass cls = new XMLParserClass();
String xmlStr = cls.generateXML();
cls.parserXML(xmlStr);
System.debug(cls.xmlDataMap);

Outcome in Debug Log


4 comments:

  1. How to write test class for 2nd and 3rd method,
    void parserXML(String toParse)
    void traverseThroughXML(DOM.XMLNode node)
    please share me test class please

    ReplyDelete
  2. @Jyothi, you should take a stab to write test class and if you find any issues then post it here or https://Salesforce.stackexchange.com

    ReplyDelete