Wednesday, August 26, 2020

Parse XML Using Apex in Salesforce

 Sample XML

<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="4.0" xmlns:edmx="http://xxx.xxx-xx.org/xx/ns/xx">
    <edmx:DataServices>
        <Schema Namespace="Person.Entities" xmlns="http://xx.xx-xxorg/xx/ns/xx">
            <EntityType Name="PersonInfo">
                <Key>
                    <PropertyRef Name="Id" />
                </Key>
                <Property Name="Id" />
                <Property Name="Name"/>
                <Property Name="FirmType"/>
                <Property Name="WebSite"/>
                <Property Name="Description"/>
                <Property Name="Address" />
                <Property Name="Address1" />
                <Property Name="HQCity" />
                <Property Name="State"/>
                <Property Name="Zip"/>
                <Property Name="CountryCode" />
                <Property Name="Phone"/>
                <Property Name="NetPatientRev"/>
                <Property Name="NetworkId"/>
                <Property Name="NetworkParentId"/>
                <Property Name="NetworkName"/>
            </EntityType>
        </Schema>
    </edmx:DataServices>
</edmx:Edmx>
Sample Code:
StaticResource res = [SELECT Id, Body From StaticResource WHERE Name = 'SmapleXML'];

String strBody = res.Body.toString();
Dom.Document doc = new Dom.Document();
doc.load(strBody);

DOM.XmlNode rootNode = doc.getRootElement();
list<String> lstNames = new list<String>();
list<DOM.xmlNode> lst = rootNode.getChildElements();

for(DOM.XmlNode re : lst) {
    if(re.getName() == 'DataServices') {
        for(DOM.XmlNode re1 : re.getChildElements()) {
            if(re1.getName() == 'Schema') {
                for(DOM.XmlNode re2 : re1.getChildElements()) {
                    if(re2.getName() == 'EntityType') {
                        if(re2.getAttribute('Name', '') == 'PersonInfo') {
                            for(DOM.XmlNode re3 : re2.getChildElements()) {
                                if(re3.getName() == 'Property') {
                                    lstNames.add(re3.getAttribute('Name', ''));
                                }
                            }
                        }
                    }
                }	
            }
        }
    }
}

System.debug('lstNames ==> '+lstNames);
Result:

1 comment:

  1. can i get the entities in salesforce in xml file

    ReplyDelete