Wednesday, July 20, 2011

DOM Classes in salesforce

DOM (Document Object Model) classes help you to parse or generate XML content. The DOM represents an XML document as a hierarchy of nodes. The best utilization of DOM classes is when a  request created by HttpRequest or to parse a response accessed by HttpResponse.

If you want to call a external webservice then you have two options in salesforce.

  • You can get the wsdl of the webservice and parse the wsdl in salesforce. It will automatically create the webservice classes and you can use the methods of those classes.
  • You can also create a soap envelope and send the request to endpoint url using HttpRequest class and then parse the HttpResponse using DOM classes.

I am taking an example of how to create a soap envelope and how to parse the response using DOM classes.


public class WebserviceRequest{
public void sendRequest(){
     String endpointUrl = ''; // please provide the endpoint url here
     
     //create a new instance of httprequest
     HttpRequest req = new HttpRequest();
     //set method
     req.setMethod('POST');

     // set endpoint url
     req.setEndpoint(endpointUrl);

     // set header
     req.setHeader('Content-Type', 'text/xml');

     // set soap envelope into request body
     req.setBody(getSoapEnvelope());
     
     // create a new instance of Http class
     Http http = new Http();
     // send request
     HttpResponse res = http.send(req);
     
     // method to parse httpresponse
     parseResponse(res);

}

// method to create envelope
public String getSoapEnvelope(){

// Note this is a sample soap request. 
String envelope = '


  
    IBM
  

' ;

return envelope ;
}

//this method is used to parse the response.
public void parseResponse(HttpResponse res)
{
 dom.document doc = res.getBodyDocument();
 dom.XmlNode [] node = doc.getRootElement().getChildElements();
 // iterate over node will return all the nodes of the xml respose.  
}

}

For more details please refer this link

Please let me know if there is any issue.

Thanks,

2 comments:

  1. Could you make the example with the following code? I would appreciate it.

    http://www.banguat.gob.gt/variables/ws/TipoCambio.asmx?op=TipoCambioDia

    ReplyDelete