我需要通过 XSLT 将 SVG 文件转换为 HTML5 Canvas 。 问题是关于 Javascript 的。 在 svg 文件中,我有一个带有一些代码的脚本标签,就像这个简单的例子一样:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="transform.xsl"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
id="slot" width="320" height="245">
<script type="application/javascript"><![CDATA[
var test = 2;
alert("This is a test!");
]]></script>
<----here svg drawing tags--->
</svg>
我想将部分修改的Javascript代码输出到html,并添加一些新代码,像这样:
<html>
<head>
<title> SVG to HTML5!</title>
<script type="application/javascript">
var new_test; <---the new code--->
var test = 4; <---this is the modified code from
alert("This is a new test!"); svg file--->
</script>
</head>
<body>
</body>
</html>
我该怎么做?
最佳答案
虽然可以编写(有些复杂的)代码来执行单独的行替换/插入/删除,但更简单的方法是替换完整的 script
元素:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pNewScript">
<script type="application/javascript">
var new_test;
var test = 4;
alert("This is a new test!");
</script>
</xsl:param>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="svg:script">
<xsl:copy-of select="$pNewScript"/>
</xsl:template>
</xsl:stylesheet>
当此转换应用于提供的 XML 文档时(更正为格式正确):
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
id="slot" width="320" height="245">
<script type="application/javascript"><![CDATA[
var test = 2;
alert("This is a test!");
]]></script>
<!-- here svg drawing tags -->
</svg>
产生了想要的、正确的结果:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
id="slot" width="320" height="245">
<script xmlns:svg="http://www.w3.org/2000/svg" type="application/javascript">
var new_test;
var test = 4;
alert("This is a new test!");
</script><!-- here svg drawing tags -->
</svg>
关于html - XSLT:如何将 Javascript 代码从 xml 复制到 html,修改其中的某些行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7938156/