3

I'm parsing XML using apex but I'm not getting text value in case when data in the form of cDATA, I'm getting an empty string. below is my code. in my case, I m getting an empty string when parsing description node.

Apex code

public class ProductImportHelper {

    Map<String, Product2> mapOfProductRecords = new  Map<String, Product2>();
    Map<String, List<Product_Image__c>> mapOfProductImageRecords = new  Map<String, List<Product_Image__c>>();
    List<Product_Image__c> listOfImageRecords = New List<Product_Image__c>();
    String id,category,brand;
    public static HttpResponse processCallout() {

        String url ='http://hansanders15fd.acc01.netivity.nl/feed/salesforce?page=1&pageSize=30';
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        req.setTimeout(60000);
        HttpResponse res = h.send(req);
        return res;
    }
    public void parseResponseDom(){
        try{
            HttpResponse res = processCallout(); // parameters endpoint, pageSize
            String XMLString = res.getBody();
            DOM.Document doc = new DOM.Document();
            doc.load(XMLString);
            DOM.XmlNode rootNode = doc.getRootElement();
            walkThrough(rootNode);
        }
        catch(Exception e) {
            system.debug('Exception :::' + e.getMessage());
        }
     //   insert mapOfProductRecords.values();

        for(Product2 product2Records : [Select id,Product_Code__c from Product2]) {

            for(Product_Image__c prodImageRecords : mapOfProductImageRecords.get(product2Records.Product_Code__c)) {
                listOfImageRecords.add(new Product_Image__c(Product__c =product2Records.id, Type__c =prodImageRecords.Type__c, Size__c=prodImageRecords.Size__c,URL__c = prodImageRecords.URL__c));
            }
        }
       // insert listOfImageRecords;
    }
    private void walkThrough(DOM.XMLNode node) {
        if (node.getNodeType() == DOM.XMLNodeType.ELEMENT) {
            if(node.getName() == 'id') {
                id = node.getText().trim();
                if(!mapOfProductRecords.containsKey(id))   {
                    mapOfProductRecords.put(id, new Product2(Product_Code__c = id,Name = 'Test', Product_Category_FR_BE__c = '', Product_Category_NL_BE__c = '', Product_Category_NL_NL__c = ''));
                    mapOfProductImageRecords.put(id, new List<Product_Image__c>() );
                }
            }
            if(node.getName() == 'brand') 
                mapOfProductRecords.get(id).Brand__c = node.getText().trim();
            if(node.getName() == 'lens_code') 
                mapOfProductRecords.get(id).Lens_Code__c = node.getText().trim();
            if(node.getName() == 'gender') 
                mapOfProductRecords.get(id).Gender__c = node.getText().trim();
            if(node.getName() == 'link') 
                mapOfProductRecords.get(id).Link__c = node.getText().trim();
            if(node.getName() == 'stock') 
                mapOfProductRecords.get(id).Stock__c =  Integer.valueOf(node.getText().trim());
            if(node.getName() == 'type') 
                mapOfProductRecords.get(id).Type__c = node.getText().trim();
            if(node.getName() == 'category'  || node.getName() == 'color' || node.getName() == 'active' || node.getName() == 'description' || node.getName() == 'link' || node.getName() == 'title') { 
                category= node.getText().trim();
                if (node.getAttributeCount() > 0) { 
                    for (Integer i = 0; i< node.getAttributeCount(); i++ ) {

                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'fr-BE' && node.getName() == 'category' ) 
                            mapOfProductRecords.get(id).Product_Category_FR_BE__c = category;
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'nl-BE' && node.getName() == 'category') 
                            mapOfProductRecords.get(id).Product_Category_NL_BE__c = category;
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'nl-NL' && node.getName() == 'category') 
                            mapOfProductRecords.get(id).Product_Category_NL_NL__c = category;
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'fr-BE' && node.getName() == 'color' ) 
                            mapOfProductRecords.get(id).Color_FR_BE__c = category;
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'nl-BE' && node.getName() == 'color') 
                            mapOfProductRecords.get(id).Color_NL_Be__c = category;
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'nl-NL' && node.getName() == 'color') 
                            mapOfProductRecords.get(id).Color_NL_NL__c = category;
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'fr-BE' && node.getName() == 'active' ) 
                            mapOfProductRecords.get(id).Active_FR_BE__c = Boolean.ValueOf(category);
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'nl-BE' && node.getName() == 'active') 
                            mapOfProductRecords.get(id).Active_NL_BE__c = Boolean.ValueOf(category);
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'nl-NL' && node.getName() == 'active') 
                            mapOfProductRecords.get(id).Active_NL_NL__c = Boolean.ValueOf(category);
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'fr-BE' && node.getName() == 'description' ) {
                            mapOfProductRecords.get(id).Description_FR_BE__c = category;
                            stripCDATA(category);

                        }

                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'nl-BE' && node.getName() == 'description') 
                            mapOfProductRecords.get(id).Description_NL_BE__c = category;
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'nl-NL' && node.getName() == 'description') 
                            mapOfProductRecords.get(id).Description_NL_NL__c = category;
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'fr-BE' && node.getName() == 'link' ) 
                            mapOfProductRecords.get(id).Link_FR_BE__c = category;
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'nl-BE' && node.getName() == 'link') 
                            mapOfProductRecords.get(id).Link_NL_BE__c = category;
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'nl-NL' && node.getName() == 'link') 
                            mapOfProductRecords.get(id).Link_NL_NL__c = category;
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'fr-BE' && node.getName() == 'title' ) 
                            mapOfProductRecords.get(id).Title_FR_BE__c = category;
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'nl-BE' && node.getName() == 'title') 
                            mapOfProductRecords.get(id).Title_NL_BE__c = category;
                        if(node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i)) == 'nl-NL' && node.getName() == 'title') 
                            mapOfProductRecords.get(id).Title_NL_NL__c = category;
                    }  
                }
            }
            if(node.getName() == 'image') {
                String type,size;
                category= node.getText().trim();
                System.debug('category----  '+category);
                if (node.getAttributeCount() > 0) { 
                    for (Integer i = 0; i< node.getAttributeCount(); i++ ) {
                        if(node.getAttributeKeyAt(i) == 'type' && node.getName() == 'image' ) {
                            type= node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i));
                        }
                        if(node.getAttributeKeyAt(i) == 'size' && node.getName() == 'image' ) {
                            size= node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i));
                        }
                    }
                    mapOfProductImageRecords.get(id).add(new Product_Image__c(Type__c = type,Size__c=size,URL__c = category));
                }
            }
            for (Dom.XMLNode child: node.getChildElements()) {
                walkThrough(child);
            }
        }
    }
    public static void parseCdata() {

        String xml =
            '<?xml version="1.0" encoding="UTF-8"?>' +
            '<root>' +
            '  <SomeNode><![CDATA[<b>contains html tags</b>]]></SomeNode>' +
            '</root>';

        // replace CDATA sections with parseable tokens
        xml = xml.replaceAll( '<!\\[CDATA\\[', 'XML_CDATA_START' ).replaceAll( ']]>', 'XML_CDATA_END' );

        // we will build up a map of original text and replacement text
        Map<String, String> replacementMap = new Map<String, String>();

        // regular expression to match sections we want to replace
        Pattern myPattern = Pattern.compile( '(XML_CDATA_START)(.*?)(XML_CDATA_END)' );
        Matcher myMatcher = myPattern.matcher( xml );

        while ( myMatcher.find() ) {
            // the regex was too complicated for Matcher.replaceFirst(..)
            // so have to do it manually so just put in this map the
            // original text and the replacement text, we do replacing later
            replacementMap.put( myMatcher.group(), myMatcher.group(2).escapeXML() );
        }

        // replace in the xml each CDATA section with the escaped XML of its inner content
        for ( String key : replacementMap.keySet() ) {
            xml = xml.replace( key, replacementMap.get( key ) );
        }

        // parse the xml like normal
        Dom.Document doc = new Dom.Document();
        doc.load( xml );

        Dom.XMLNode rootNode = doc.getRootElement();
        String text = rootNode.getChildElement( 'SomeNode', null ).getText();
        System.debug( 'cprse data --  '+text ); // prints: <b>contains html tags</b>
    }


    public String stripCDATA(String str) {
        Pattern p = Pattern.compile('<!\\[CDATA\\[(.*?)\\]\\]>');
        Matcher m = p.matcher(str);
        while(m.find()) {
            str = str.replace(m.group(), m.group(1).escapeXml());
        }
        System.debug('str 9999999  '+str);
        return str;
    }
}

1 Answer 1

3

According to this idea, CDATA isn't supported. It also includes a workaround you can use for now:

public String stripCDATA(String str) {
    Pattern p = Pattern.compile('<!\\[CDATA\\[(.*?)\\]\\]>');
    Matcher m = p.matcher(str);
    while(m.find()) {
        str = str.replace(m.group(), m.group(1).escapeXml());
    }
    return str;
}

Do this before loading the data in to your Dom.Document.

0

You must log in to answer this question.

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