xmlHttpRequest忽略SVG中的g元素

时间:2016-09-17 00:20:49

标签: javascript svg xmlhttprequest

我在Inkscape中创建了一个SVG文件。我想使用xmlHttpRequest导入svg文件,然后将<g>元素中的数据注入HTML。

但是。由于某种原因,xml响应省略了g元素。当我在浏览器的调试控制台中评估XMLResponse时,我可以看到这一点。为什么会发生这种情况,我该如何解决?

这是XMLResponse推出的内容 Here's what the XMLResponse puts out

SVG

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" height="7e3" width="7e3" version="1.1" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" viewBox="0 0 7000 7000">
    <metadata>
        <rdf:RDF>
            <cc:Work rdf:about="">
                <dc:format>image/svg+xml</dc:format>
                <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
                <dc:title/>
            </cc:Work>
        </rdf:RDF>
    </metadata>
    <g>
        <path d="m2757.3 5004.4-680.5-398.2-481.1 1037.3 168.3-770.3-1135.1-137 784.6-77.9-220.5-1122l316.57 722.13 998.9-556.4-588.96 524.23z" fill="#b80000"/>
        <path d="m3412.4 2163.2-160.35-542.71-560.16-80.386 466.6-320.21-96.649-557.59 448.72 344.81 500.43-264.22-189.27 533.31 405.93 394.29-565.7-15.206z" fill="#c5e100"/>
        <path d="m5368.2 4458.8-2316.6-2010.7 2271.3 3360.5-934.5-1243.8-1614.2 420 2282.8-768.5-2327 530.8 2258.9 1074.5-149.6-2017.6 490.3-524.8-2267.1 1484.9 2756.7-1066.1-2366.8 1127 1764.8 768.5 723-848.5-721.5-2303.9z" transform="matrix(.81493 0 0 .84227 1190.8 811.58)" fill="#1643bf"/>
    </g>
</svg>

的Javascript

var svg = document.getElementsByTagName("svg")[0];
var g = svg.getElementsByTagName("g")[0];

xmlHTTP = new XMLHttpRequest();
xmlHTTP.onload = function() {
 if (this.readyState == 4 && this.status == 200) {
     draw();
};
xmlHTTP.open("GET", "drawing.svg", true);
xmlHTTP.send();

function draw(){
  var svgFile, extG;
  svgFile = xmlHTTP.responseXML;// <---evaluates without the g element from the svg file
  extG = svgFile.getElementsByTagName("g");
  svg.replaceChild(extG[0],g);
};

1 个答案:

答案 0 :(得分:0)

正如我在评论中指出的那样,在将SVG作为DOM对象之前,不能在SVG上使用常规Dom方法。

最好的方法是:

var svg=httpresponse.getDocumentElement();
var g=svg.getElementsByTagName('g');

变量g将包含g元素的实时集合。