主要问题似乎是将 SVG 片段放入 SVG 命名空间。您可以使用 XSLT 来“完成” SVG(添加周围的 svg 元素)并将所有内容放在正确的命名空间中:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/2000/svg" version="1.0">
<!-- The dimension can be supplied using a parameter.
This defaults to 100%. -->
<xsl:param name="width" select="'100%'"/>
<xsl:param name="height" select="'100%'"/>
<xsl:template match="/">
<svg version="1.1" width="{$width}" height="{$height}">
<xsl:apply-templates/>
</svg>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}" namespace="http://www.w3.org/2000/svg">
<xsl:apply-templates select="node()|@*"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*|text()">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
您必须使用 AJAX 加载样式表和 SVG 片段
使用 AJAX 获取 SVG 片段,例如:
var loadXML = function(fileName,mime) {
xmlHttpRequest = new XMLHttpRequest()
xmlHttpRequest.open("GET",fileName,false);
xmlHttpRequest.send("");
return xmlHttpRequest.responseXML;
}
var svgSnippet = loadXML(snippetURL,"image/svg+xml")
var xslt = loadXML(xsltURL,"application/xslt+xml")
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xslt);
// You can override the default width/height parameters here
xsltProcessor.setParameter(null,"width","150px")
xsltProcessor.setParameter(null,"width","90px")
// In the document there must be some element to append the SVG
documentGetElementById("svgContainer").appendChild(xsltProcessor.transformToFragment(svgSnippet,document).firstChild)
这一切都未经测试,但也许可以开始。如果您还需要 XLink 命名空间,这当然是不完整的。