5

我正在尝试使用document.evaluate()从元素中提取某些子元素<svg>。但是我只是提取<svg>本身就有问题。我可以将所有内容提取到<svg>,但不能再进一步了。例如,这很好用:

document.evaluate('//*[@id="chart"]/div/div[1]/div', document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue)

这给了我(缩短):

<div style="position: absolute; left: 0px; top: 0px; width: 100%; height: 100%;" aria-label="Et diagram.">
    <svg width="600" height="400" aria-label="Et diagram." style="overflow: hidden;"></svg>
    <div aria-label="En repræsentation i tabelformat af dataene i diagrammet." style="position: absolute; left: -10000px; top: auto; width: 1px; height: 1px; overflow: hidden;"></div>
</div>

然后我会假设简单

//*[@id="chart"]/div/div[1]/div/svg

会给我<svg>- 但没有任何效果。已尝试所有响应类型:

for (var type=XPathResult.ANY_TYPE; type<XPathResult.FIRST_ORDERED_NODE_TYPE+1; type ++) {
   console.dir(
      document.evaluate('//*[@id="chart"]/div/div[1]/div/svg', document, null, type, null)
   );   
}    

我得到invalidIteratorState, nullsingleNodeValue或 a snapshotLengthof 0。

演示-> http://jsfiddle.net/hw79zp7j/

有没有evaluate()我没有听说过的限制,或者我只是做错了?

为了澄清,我的最终目标是能够xAxis <text>在一行代码中提取例如谷歌可视化元素。就像现在一样(参见演示),我必须<svg>使用多个querySelectorAll/getElementsByTagName等来迭代,这不是很可读,维护友好或优雅。xpath从谷歌开发者工具中获取并在一行中重用它会很好。

4

1 回答 1

5

SVG 元素位于命名空间中http://www.w3.org/2000/svg,要使用 XPath 选择命名空间中的元素,您需要将前缀绑定到命名空间 URI,并在路径中使用该前缀来限定元素名称,例如svg:svg. 因此,使用解析器作为第三个参数evaluate,它将您可以选择的前缀(例如svg)映射到上述命名空间 URI。

document.evaluate('//*[@id="chart"]/div/div[1]/div/svg:svg', document, 
                                function(prefix) { 
                                    if (prefix === 'svg') 
                                    { 
                                        return 'http://www.w3.org/2000/svg';
                                    }
                                    else
                                    {
                                        return null;
                                    }
                                }, type, null)
于 2015-07-01T13:31:56.660 回答