function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
dujsudujsu 

XML String to Dom.XMLNode - is it possible to convert?

Hello,

 

Im working on a test class for an external webservice and having issues with converting a dummy XML (String) into a Type Dom.XMLNode. I need to figure out a way to kick off the 'walkthrough' method from my test class in order to get my percentages up. So any advice is appreciated.

 

Test class - based on this article here: http://sfdc.arrowpointe.com/2009/05/01/testing-http-callouts/

 

 

... 
try { 
 if(!isApexTest){ 
    HTTPResponse res = http.send(req); 
    Dom.Document doc = res.getBodyDocument(); 
    Dom.XMLNode root = doc.getRootElement(); 
 }else{ 
    //error occurs here because Im trying to give DOM.XMLNode a String

    DOM.XMLNode root = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><AddFolderResponse xmlns="http://blahns"><AddFolderResult><<ObjectID>​1234567890</ObjectID></AddFolderResult></AddFolder​Response></soap:Body></soap:Envelope>'; 
 } 
 xObjectID = walkthrough(root, 'ObjectID').trim();

  return xObjectID; 

} catch(System.CalloutException e){ 
  return e.getMessage(); 
} 
...

 

 

 

Walkthrough Method: based on article found here:  http://developer.force.com/cookbook/recipe/parsing-xml-using-the-apex-dom-parser

 

	public static String walkThrough(DOM.XMLNode node, String field) {
		String result = '\n';
		
		if(node.getNodeType() == DOM.XMLNodeType.ELEMENT) {
			
			if(node.getName().trim() == field) {
				result += node.getText().trim();
			}
			
			for(DOM.XMLNode child : node.getChildElements()) {
				result += walkThrough(child, field);
			}
			return result;
		}
		return 'ERROR';
	}

 

 

Best Answer chosen by Admin (Salesforce Developers) 
dujsudujsu

Figured it out. I needed to "load" the XML to the Document.

 

...
}else{
  String expectedResult = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><AddFolderResponse xmlns="http://blahns"><AddFolderResult><<ObjectID>​1234567890</ObjectID></AddFolderResult></AddFolder​Response></soap:Body></soap:Envelope>';
  Dom.Document doc = new Dom.Document();
  doc.load(expectedResult);
  Dom.XMLNode root = doc.getRootElement();	 
  xObjectID = walkthrough(root, 'ObjectID').trim();
}
..