问题描述
我正在尝试使用 document.evaluate()
从< svg> 元素。但是我只是通过提取
< svg>
本身来解决问题。我可以将所有内容提取到< svg>
,但不能再提取。例如,这很有效:
I am trying to use
document.evaluate()
to extract certain child elements out of a <svg>
element. But I have problems by just extracting the <svg>
itself. I can extract everything up to the <svg>
, but no further. For example this works well :
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>
- 但没有任何作用。尝试了所有响应类型:
would give me the
<svg>
- but nothing works. Have tried all respond types :
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
,null singleNodeValue
或 snapshotLength
为0.
I get either
invalidIteratorState
, null singleNodeValue
or a snapshotLength
of 0.
demo - >
demo -> http://jsfiddle.net/hw79zp7j/
是否有任何限制
evaluate()
我没有听说过,或者我只是完全错了?
Is there any limitations of
evaluate()
I havent heard of, or am I just doing it utterly wrong?
为了澄清,我的最终目标是能够提取例如谷歌可视化
code> getElementsByTagName 等,这不是非常易读,维护友好或优雅。从谷歌开发者工具中获取 xAxis
<文本>
单行代码中的元素。就像现在一样(参见演示)我必须使用多个 querySelectorAll
/ < svg> xpath
并在一行中重复使用它会很不错。
For clarification, my ultimate goal is to be able extract for example a google visualization xAxis
<text>
elements in a single line of code. As it is now (see demo) I have to iterate through the <svg>
by using multiple querySelectorAll
/ getElementsByTagName
etc, which is not very readable, maintenance friendly or elegant. It would be nice just to grab the xpath
from google developer tools and reuse it in a single line.
推荐答案
SVG元素位于命名空间 http://www.w3.org/2000/svg
中,并使用XPath选择命名空间中的元素您需要将前缀绑定到名称空间URI,并在路径中使用该前缀来限定元素名称,例如 SVG:SVG
。因此,使用解析器作为 evaluate
的第三个参数,将您可以选择的前缀(例如 svg
)映射到命名空间上面提到的URI。
SVG elements are in the namespace http://www.w3.org/2000/svg
and to select elements in a namespace with XPath you need to bind a prefix to the namespace URI and use that prefix in your path to qualify the element names e.g. svg:svg
. So use a resolver as the third argument of evaluate
that maps the prefix you can choose (e.g. svg
) to the namespace URI mentioned above.
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)
这篇关于提取< svg>元素使用document.evaluate()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!