Friday, September 20, 2013

XML Node Class in Salesforce

XmlNode Class:

Use the XmlNode class to work with a node in an XML document. The DOM represents an XML document as a hierarchy
of nodes. Some nodes may be branch nodes and have child nodes, while others are leaf nodes with no children.

Node Types:
There are different types of DOM nodes available in Apex. XmlNodeType is an enum of these different types. The values

It is important to distinguish between elements and nodes in an XML document. The following is a simple XML example:


This example contains three XML elements: name, firstName, and lastName. It contains five nodes: the three name,
firstName, and lastName element nodes, as well as two text nodes—Suvain and Singh. Note that the text within an
element node is considered to be a separate text node.


The XmlNode class has the following methods:

XmlNode Example:

This example shows how to use XmlNode methods and namespaces to create an XML request.

public class DomNamespaceSample
public void sendRequest(String endpoint)
// Create the request envelope
DOM.Document doc = new DOM.Document();
String soapNS = '';
String xsi = '';
String serviceNS = '';
dom.XmlNode envelope
= doc.createRootElement('Envelope', soapNS, 'soapenv');
envelope.setNamespace('xsi', xsi);
envelope.setAttributeNS('schemaLocation', soapNS, xsi, null);
dom.XmlNode body
= envelope.addChildElement('Body', soapNS, null);
body.addChildElement('echo', serviceNS, 'req').
addChildElement('category', serviceNS, null).
// Send the request
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type', 'text/xml');
Http http = new Http();
HttpResponse res = http.send(req);
System.assertEquals(200, res.getStatusCode());
dom.Document resDoc = res.getBodyDocument();
envelope = resDoc.getRootElement();
String wsa = '';
dom.XmlNode header = envelope.getChildElement('Header', soapNS);
System.assert(header != null);
String messageId= header.getChildElement('MessageID', wsa).getText();
System.debug(messageId); System.debug(resDoc.toXmlString()); System.debug(resDoc); System.debug(header); System.assertEquals( '', header.getChildElement( 'ReplyTo', wsa).getChildElement('Address', wsa).getText()); System.assertEquals( envelope.getChildElement('Body', soapNS). getChildElement('echo', serviceNS). getChildElement('something', 'http://something.else'). getChildElement( 'whatever', serviceNS).getAttribute('bb', null), 'cc'); System.assertEquals('classifieds', envelope.getChildElement('Body', soapNS). getChildElement('echo', serviceNS). getChildElement('category', serviceNS).getText()); } }

No comments:

Post a Comment