I get data in XML from a web service from a connector URL, the xml contains data about people, now I have to read the names, emailids from that xml and compare with my org's contacts and so some operations. So how do I read it?
[SalesForce] How to read XML data in salesforce
Related Solutions
I figure out how can I do it.. I just wanted to share my answer, see full code below:
class Cell {
string data { get; set; }
}
Integer rowCounter = 0;
List<Cell> cellDataList = new List<Cell>();
Map<Integer, List<Cell>> rowDataMap = new Map<Integer, List<Cell>>();
XmlStreamReader xsr = new XmlStreamReader(reportXML);
while(xsr.hasNext()) {
if (xsr.getEventType() == XmlTag.START_ELEMENT) {
if(xsr.getLocalName() == 'Row') {
rowCounter++;
rowDataMap.put(rowCounter, cellDataMap);
cellDataList = new List<Cell>();
}
if (xsr.getLocalName() == 'Cell') {
Cell cell = parseCell(xsr);
cellDataList.add(cell);
}
}
xsr.next();
}
Cell parseCell(XmlStreamReader reader) {
Cell cell = new Cell();
while(reader.hasNext()) {
if (reader.getEventType() == XmlTag.END_ELEMENT)
break;
else if (reader.getEventType() == XmlTag.CHARACTERS)
cell.data = reader.getText();
reader.next();
}
return cell;
}
for (Integer rowKey : rowDataMap.keySet()) {
if (!rowDataMap.get(rowKey).isEmpty()) {
system.debug('===============ROW Start====================');
for (Cell cells : rowDataMap.get(rowKey)) {
system.debug(cells);
}
system.debug('===============ROW End====================');
}
}
Do I have to list all the fields as parameters in the method or is there a way to use DOMElement as a parameter while defining the method and then I go about extracting the data out of it.
One Approach is like declare your http post
method with no parameters and when you pass the XML request body it will be copied in the RestRequest.requestBody
as Blob.Then you can convert to string and pass it Dom.Document.load()
something like below and parse it.
@RestResource(urlMapping='/api/*/createContact')
global with sharing class RESTAPI_JSON_XML{
@httppost
global static void doPost(){
RestRequest req = RestContext.request;
system.debug('XML String---'+req.requestBody.toString());
DOM.Document doc=new DOM.Document();
doc.load(req.requestBody.toString());
DOM.XmlNode rootNode=doc.getRootElement();
//XML Parsing
}
}
Best Answer
You need either
Dom
orXmlStreamReader
class to parse your xml response. You can find sample code in the below links.Xml parsing using XmlStreamReader:- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_xml_streaming_reading.htm
Xml parsing using Dom:- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_xml_dom.htm