Chrome和Firefox无法在SVG <foreignobject>元素上评估XPath

时间:2016-11-09 04:03:15

标签: google-chrome firefox xpath

示例SVG:

<svg width="100%" height="500" xmlns="http://www.w3.org/2000/svg">
  <foreignObject x="10" y="10" width="100" height="150">
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <title>title</title>
      </head>
    </html>
  </foreignObject>
</svg>

在控制台中执行以下脚本时返回null

document.evaluate("/svg/foreignObject/html", document,
    null, XPathResult.ANY_TYPE, null).iterateNext() 

XPath或document.evaluate()来电有什么问题吗?

1 个答案:

答案 0 :(得分:1)

您的XML在不同的元素级别定义了2个默认命名空间。在this MDN article中使用document.evaluate()时,您可以阅读有关处理命名空间的信息。基本上,您需要将默认名称空间URI映射的前缀定义为名称空间解析器函数:

function nsResolver(prefix) {
  var ns = {
    'xhtml' : 'http://www.w3.org/1999/xhtml',
    'svg': 'http://www.w3.org/2000/svg'
  };
  return ns[prefix] || null;
}

使用上面的前缀来引用XPath中相应命名空间中的元素,并将命名空间解析器与XPath一起传递:

document.evaluate("/svg:svg/svg:foreignObject/xhtml:html", 
                    document, nsResolver, XPathResult.ANY_TYPE, null)