How to add a comment node before the root <svg>
element but after the xml prolog?
Or will it be less resource expensive to insert the comment with a regexp on the serialized DOM?
How to add a comment node before the root <svg>
element but after the xml prolog?
Or will it be less resource expensive to insert the comment with a regexp on the serialized DOM?
Like below?
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- sample comment in SVG file
can be multi-line
-->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<circle cx="100" cy="110" r="40" style="fill: #FF0"/>
<circle cx="100" cy="210" r="30" style="fill: none; stroke: #F00; stroke-width: 2px"/>
</svg>
The root element (ie, exclusive of xml prologs and DTDs) is in documentElement
. You can use insertBefore
with it:
var s = '<?xml version="1.0" encoding="ISO-8859-1"?>\n' +
'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"\n' +
' "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
'<svg width="100%" height="100%" version="1.1" ' +
' xmlns="http://www.w3.org/2000/svg">\n' +
' <circle cx="100" cy="50" r="40" stroke="black" ' +
' stroke-width="2" fill="red"/>\n' +
'</svg>',
doc = new DOMParser().parseFromString(s, 'text/xml');
// insert a comment node before the root node
doc.insertBefore(doc.createComment('foo'), doc.documentElement);
To check, new XMLSerializer().serializeToString(doc)
outputs:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!--foo-->
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
</svg>
Note that some browsers (WebKit I believe) will ommit the prolog from the serialized output (it's optional anyway). However the comment node is still present after the DTD.
As to which is less expensive, I'm not sure. If you don't need the string in DOM form for anything other than this one thing, it may not be worth going through the DOM parser (especially just to serialize it back to a string anyway).