35

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.

0

1 Answer 1

85

You can do this by serializing just the root node:

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

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

Sign up to request clarification or add additional context in comments.

5 Comments

There should be a 'save this answer somewhere because you're going to search for it another million times' button in SO...
@Nathan you can click on "Bookmark this question" and in your profile you will find those under "Bookmarks".
@Patric, nearly six years later it turned out that I didn't search for anything XML-related quite as much... But thanks for the tip, I didn't know about that!
Why not just xmlObject.documentElement.outerHTML?
@AaronJ: AFAICT, there's no reason not to use that now, given that it is standardized and works on XML. Historically, outerHTML was non-standard for years while XMLSerializer existed. I'm having a hard time finding out whether it was standardized by 2013, and if so, whether it could be relied upon for XML documents as well as HTML. Personally, I'd probably still use XMLSerializer because the name is more suggestive of its purpose than outerHTML; outerHTML would catch my eye as being potentially wrong in XML-related code and I'd have to look it up, which makes it less readable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.