Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting XMLDocument object to String in Javascript

Tags:

javascript

xml

I want to convert XMLDocument object that I'm getting as a response from an ajax request, to a string. I tried using

new XMLSerializer()).serializeToString(xmlObject) 

and I get the following response:-

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><ns2:errorList xmlns:ns2="http://www.example.com/api/delivery/V1"><error code="DOMAIN_VALIDATE" path="delivery.shipper"><message>empty</message></error><error code="DOMAIN_VALIDATE" path="delivery.shipperSite"><message>empty</message></error><error code="DOMAIN_VALIDATE" path="delivery.leg"><message>invalid</message></error></ns2:errorList> 

Means the method converted the whole XMLDocument into string, including the very first tag

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 

I don't want this part of the response. Is there any method that does that. Note: I don't want to use the workarounds like "substr" etc.

like image 425
paras2682 Avatar asked Jul 16 '13 07:07

paras2682


People also ask

How to Convert XML object to String in Javascript?

toXMLString() This method converts an XML object into a valid XML string. You must use the other XML get methods to navigate through an XML document.

How do I read XML files?

If all you need to do is view the data in an XML file, you're in luck. Just about every browser can open an XML file. In Chrome, just open a new tab and drag the XML file over. Alternatively, right click on the XML file and hover over "Open with" then click "Chrome".


1 Answers

You can do this by serializing just the root node:

new XMLSerializer().serializeToString(xmlObject.documentElement); 

Demo: http://jsfiddle.net/timdown/LmWkL/

like image 181
Tim Down Avatar answered Sep 20 '22 08:09

Tim Down