2
我想添加SVG,其中包含矩形和使用標記從字符串到DOM。如何將字符串中的SVG元素添加到DOM
我不接縫以我的方式工作。
\t \t var documentAsString =
\t \t '<?xml version="1.0" encoding="UTF-8"?>\
\t \t \t <document xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\
\t \t \t \t <svg id="container" >\
\t \t \t \t \t <g xmlns:xlink="http://www.w3.org/1999/xlink">\
\t \t \t \t \t \t <rect x="50" y="50" width="50" height="50" fill="red"/>\
\t \t \t \t \t \t <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#shape" x="200" y="50" fill="blue"></use>\
\t \t \t \t \t </g>\
\t \t \t \t </svg>\
\t \t \t </document>\
\t \t ';
\t \t
\t \t var newDocument = (new DOMParser()).parseFromString(documentAsString, "text/xml");
\t \t var container = newDocument.getElementById("container");
\t \t var useContainer = document.getElementById('use-container');
\t \t useContainer.removeChild(useContainer.firstElementChild);
\t \t useContainer.appendChild(container.getElementsByTagName('g')[0]);
\t <svg>
\t \t <defs>
\t \t \t <g id="shape">
\t \t \t \t <rect x="50" y="50" width="50" height="50" />
\t \t \t \t <circle cx="50" cy="50" r="50" />
\t \t \t </g>
\t \t </defs>
\t \t <use xlink:href="#shape" x="50" y="50" />
\t \t <g id="use-container" xmlns:xlink="http://www.w3.org/1999/xlink">
\t \t \t <rect x="10" y="10" width="50" height="50" fill="red"></rect>
\t \t </g>
\t </svg>
好的,那你有這個解釋嗎?是否因爲'container.getElementsByTagName('g')[0]'不會被視爲SVG元素? – Charles
這就是XML的工作原理。您需要告訴XML解析器,svg標籤是SVG,而不是其他標記的標籤。例如,XML解析器是如何區分SVG''標籤和html標籤''的。另一方面,html有一個解析器,它從上下文中推斷出命名空間。 –