0

/////////////////////////////////////////////RSS.xml

<rss version="2.0">
<channel>
<title>W3Schools Home Page</title>
<link>https://www.w3schools.com</link>
<description>Free web building tutorials</description>
<item>
<title>RSS Tutorial</title>
<link>https://www.w3schools.com/xml/xml_rss.asp</link>
<description>New RSS tutorial on W3Schools</description>
</item>
<item>
<title>XML Tutorial</title>
<link>https://www.w3schools.com/xml</link>
<description>New XML tutorial on W3Schools</description>
</item>
</channel>
</rss>

public class DomDocument {

// Pass in the URL for the request
// For the purposes of this sample,assume that the URL
// returns the XML shown above in the response body
public void parseResponseDom(String url){
    Http h = new Http();
    HttpRequest req = new HttpRequest();
    // url that returns the XML in the response body
    req.setEndpoint(url);
    req.setMethod('GET');
    HttpResponse res = h.send(req);
    Dom.Document doc = res.getBodyDocument();
    //Retrieve the root element for this document.
    Dom.XMLNode address = doc.getRootElement();
    System.debug('address'+address);

    Dom.XMLNode channel = address.getChildElement('channel', null);
    String title = channel.getChildElement('title', null).getText();
    system.debug('==title=='+title);
    String link = channel.getChildElement('link', null).getText();
    system.debug('==link=='+link);
    String description = channel.getChildElement('description', null).getText();
    system.debug('==description=='+description);
    for(Dom.XMLNode child : channel.getChildElements()) {
        System.debug('===30==='+child.getText());

    }
    for ( Dom.XMLNode childElement : channel.getChildElements() ) {              
        for (Dom.XMLNode detailElement : childElement.getChildElements())                                  

                system.debug( '==38=='+detailElement.getName() + '-' + detailElement.getText() );  

    }  
}

}


This is my Apex class I am calling this method from the anonymous window. I am getting the response and I have now updated my code.Now I am able to read the data.Data is now coming in debug. Can someone please help me to parse the data.

2
  • What's the error message you are getting? Apr 27, 2020 at 18:58
  • I am getting null on item.I have pasted screenshot of my xml file.I want the contents in item and also parse it into json. Apr 27, 2020 at 19:02

1 Answer 1

1

You can convert this XML to JSON using a simple parsing script that I wrote a number of years ago for this purpose.

String xmlString = '<?xml version="1.0"?><rss version="2.0"><channel><title>W3Schools Home Page</title><link>https://www.w3schools.com</link><description>Free web building tutorials</description><item><title>RSS Tutorial</title><link>https://www.w3schools.com/xml/xml_rss.asp</link><description>New RSS tutorial on W3Schools</description></item><item><title>XML Tutorial</title><link>https://www.w3schools.com/xml</link><description>New XML tutorial on W3Schools</description></item></channel></rss>';
Dom.Document xmlData = new Dom.Document();
xmlData.load(xmlString);
System.debug(
    XmlToJson.parseDocumentToJson(xmlData)
);

If you want a native object for use in Apex, you can do that, too, via parseDocumentToMap.

Here's a copy of the original utility.

global class XmlToJson {
    public String xmlText { get; set; }
    public String getJsonText() {
        try {
            Dom.Document doc = new Dom.Document();
            doc.load(xmlText);
            return parseDocumentToJson(doc);
        } catch(Exception e) {
            return '';
        }
    }

    //  Try to determine some data types by pattern
    static Pattern 
        boolPat = Pattern.compile('^(true|false)$'),  decPat = Pattern.compile('^[-+]?\\d+(\\.\\d+)?$'), 
        datePat = Pattern.compile('^\\d{4}.\\d{2}.\\d{2}$'), 
        timePat = Pattern.compile('^\\d{4}.\\d{2}.\\d{2} (\\d{2}:\\d{2}:\\d{2} ([-+]\\d{2}:\\d{2})?)?$');
    //  Primary function to decode XML
    static Map<Object, Object> parseNode(Dom.XmlNode node, Map<Object, Object> parent) {
        //  Iterate over all child elements for a given node
        for(Dom.XmlNode child: node.getChildElements()) {
            //  Pull out some information
            String nodeText = child.getText().trim(), name = child.getName();
            //  Determine data type
            Object value = 
                //  Nothing
                String.isBlank(nodeText)? null:
            //  Try boolean
            boolPat.matcher(nodeText).find()? 
                (Object)Boolean.valueOf(nodeText):
            //  Try decimals
            decPat.matcher(nodeText).find()?
                (Object)Decimal.valueOf(nodeText):
            //  Try dates
            datePat.matcher(nodeText).find()?
                (Object)Date.valueOf(nodeText):
            //  Try times
            timePat.matcher(nodeText).find()? 
                (Object)DateTime.valueOf(nodeText):
            //  Give up, use plain text
            (Object)nodeText;
            //  We have some text to process
            if(value != null) {
                //  This is a pluralized word, make list
                if(name.endsWith('s')) {
                    // Add a new list if none exists
                    if(!parent.containsKey(name)) {
                        parent.put(name, new List<Object>());
                    }
                    // Add the value to the list
                    ((List<Object>)parent.get(name)).add(value);
                } else {
                    //  Store a new value
                    parent.put(name, value);
                }
            } else if(child.getNodeType() == Dom.XmlNodeType.ELEMENT) {
                //  If it's not a comment or text, we will recursively process the data
                Map<Object, Object> temp = parseNode(child, new Map<Object, Object>());
                //  If at least one node was processed, add a new element into the array
                if(!temp.isEmpty()) {
                    //  Again, create or update a list
                    if(parent.containsKey(name)) {
                        try {
                            //  If it's already a list, add it
                            ((List<Object>)parent.get(name)).add(temp);
                        } catch(Exception e) {
                            //  Otherwise, convert the element into a list
                            parent.put(name, new List<Object> { parent.get(name), temp });
                        }
                    } else {
                        //  New element
                        parent.put(name, temp);
                    }
                }
            }
        }
        return parent;
    }
    //  This function converts XML into a Map
    global static Map<Object, Object> parseDocumentToMap(Dom.Document doc) {
        return parseNode(doc.getRootElement(), new Map<Object, Object>());
    }
    //  This function converts XML into a JSON string
    global static String parseDocumentToJson(Dom.Document doc) {
        return JSON.serializePretty(parseDocumentToMap(doc));
    }
    //  This function converts XML into a native object
    //  If arrays are expected, but not converted automatically, this call may fail
    //  If so, use the parseDocumentToMap function instead and fix any problems
    global static Object parseDocumentToObject(Dom.Document doc, Type klass) {
        return JSON.deserialize(parseDocumentToJson(doc), klass);
    }
}
2
  • Hi @sfdcfox I am looking to parse by response data in salesforce apex. Apr 27, 2020 at 20:53
  • 1
    @AnishKumar Yes, this is Apex code.
    – sfdcfox
    Apr 27, 2020 at 20:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .