By Pankaj Mehra
Salesforce frequently needs to be integrated with external systems. XML is usually employed to carry the payload between the systems.
This article shows we can recursively parse a multi level XML document on the basis of levels defined in custom settings. The advantage in using custom settings is that it’s easier to add and modify custom settings if the XML structure changes..
Components of the parsing Utility
- Custom Setting (Resume_hierarchy)
- Utility class (Include code of parsing)
- Create Mapping in custom setting : This mapping in the custom setting indicates which XML Tag is mapped to which field (SFDC object field) and which XML tag is the parent tag.
For example : We have a case where we have to parse all the information in the XML document that we receive from a webservice in the Contact object. Below is the format of the XML that we receive.
|Name||ParentTag||SubTags||Mapped To Contact Field|
- ParentTag: Custom settings can hold mappings for different custom/standard objects at the same time
The format of the parent tag field is: ContactInfo-TAGFOR-Contact (XMLTagName – TAGFOR- Custom/Standard object API name)
- SubTags: These are comma separated values of all the child tags for the parent tags name mentioned in the ParentTag field for the record.
In the above mapping for first row you can see PersonName and ContactMethod tags are child tags of ContactInfo tag.
- Mapped To Contact Field: Mapped custom/standard object field the tags. In the case where the XML tag is a parent of another tag then we have to put “NotMapped” to the corresponding mapped value. This indicates to the parsing utility to drill down in that tag for more subtags.
To use the utility here is a sample code:
[snippet caption=”Parsing Xml”]
Note :resumeXml hold the XML in String format
Dom.Document domDoc = new Dom.Document();
Dom.XMLNode resume = domDoc.getRootElement();
Contact contact = new Contact();
The result of the above XML parsing:
The contact records fields will now be populated with all the information in the XML document.
Note : The field types of SFDC Object fields are identified, and XML tags are casted in the appropriate field type at runtime with the help of describe API.
Learning to navigate XML is an important skill for Salesforce developers. We hope that these examples can help you on your journey to better integrations.