Difference between response.responseXML.getElementsByTagName(); and response.responseXML.documentEle

vinuth v
Tera Expert

Hi All,

 

What is the difference between 

var result = response.responseXML.documentElement.getAttribute("result "); and 

var result = response.responseXML.getElementsByTagName("result");

 

and which situation we using this documentElement.getAttribute() and getElementsByTagName()

 

Please any one provide the difference.

Thanks in advance,

Vinuth

3 REPLIES 3

DrewW
Mega Sage
Mega Sage

Anand Kumar P
Giga Patron
Giga Patron

Hi @vinuth v,


1.response.responseXML.documentElement.getAttribute("result"):
• This code is used to retrieve the value of an attribute named “result” from the root element of an XML document (responseXML). It assumes that the XML document has a root element with an attribute named “result.”
2.response.responseXML.getElementsByTagName("result"):
• This code is used to retrieve a NodeList containing all elements with the tag name “result” from the XML document. It returns an array-like structure that holds all matching elements in the document.

Now, in ServiceNow, you might use these functions in different scenarios:

•response.responseXML.documentElement.getAttribute("result") would be used when you have a specific XML structure with an attribute on the root element, and you want to extract the value of that attribute.

Example:

var result = response.responseXML.documentElement.getAttribute("result");

 

•response.responseXML.getElementsByTagName("result") is used when you want to retrieve all elements with a specific tag name from the XML document. This is useful when you have multiple elements with the same tag name and need to process them all.

Example:

var resultElements = response.responseXML.getElementsByTagName("result");

Please mark this as solution proposed and helpful if it’s serves your purpose.

Thanks,

Anand

ChrisBurks
Mega Sage

@vinuth v,

I don't think that either of the two will ever work. At least not with an out-of-box set up.

Here's the reason why.

If you were to not dot-walk all the way through the response and log out the full response object, you'll see the XML document that it brings back. The XML document only contains a tag (node) named "xml" with an attribute called "answer". The attribute "answer" is what holds the result. So the correct statement would be:

var result = response.responseXML.documentElement.getAttribute("answer")

 

getXML_example.png

 

With that said, ServiceNow provides other methods so that you don't have to use that long dot-walked method.

There are:

  • .getXMLAnswer
  • .getAnswer

Reference: https://developer.servicenow.com/dev.do#!/reference/api/utah/client/c_GlideAjaxAPI?navFilter=Glide