views:

184

answers:

2

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?

A: 

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"&gt;
  <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>
Lukman
Yes, like this, but I meant insert with javascript to the DOM. insertBefore() won't work since there's no parent element for `<svg>`.
Spadar Shut
+1  A: 

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"&gt;\n' +
        '<svg width="100%" height="100%" version="1.1" ' +
        '     xmlns="http://www.w3.org/2000/svg"&gt;\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"&gt;
<!--foo-->
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg"&gt;
  <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).

Crescent Fresh
Thanks a lot! That's exactly what i need!I make an SVG viewer opera widget(http://my.opera.com/SpShut/blog/2010/01/05/opera-svg-viewer-widget-v0-3b), and Opera inserts xml prolog. I need DOM to get width/height/viewBox attributes, so it will be best to work wit DOM. Many thanks!
Spadar Shut