Question

up to now, whenever I wanted to obtain the XML text that a DOM object represented, I used the .serializeToString() method. Example:

var dom = require('xmldom').DOMParser;
var s = require('xmldom').XMLSerializer;

myNode = new dom().parseFromString('<greet>Hello!</greet>', 'text/xml');
console.log(new s().serializeToString(myNode, 'text/xml');

However, I have accidentally discovered that all node objects also have a .toString() method which, apparently, returns exactly the same thing as the serializer.

console.log(myNode.toString());

What is the point of going through the serializer? Is it best practice? Are there any important differences (for example, treatment of special characters like '<')? Anything else I should be made aware of?

Thanks!!

Was it helpful?

Solution

The short answer is that if you are only using this code on Node, then you are free to use either node.toString() or new XMLSerializer().serializeToString(node).

The toString method is however non-standard, and does not exist in browsers. The DOMParser spec only specifies the parsing/serializing in a few ways and toString is not one of them. As you can see in XMLDOM, it is just an alias to serializeToString:

https://github.com/jindw/xmldom/blob/master/dom.js#L911

Also note that serializeToString does not have a second argument, so you don't need the second text/xml.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top