2016-11-09 87 views
1

樣品SVG的XPath:Chrome和Firefox無法評估對SVG <foreignObject>元素

<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

您的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)