2012-03-03 71 views
3

我有几个带有1-n Path元素的svg文档,现在我想更改这些路径元素的颜色。使用XSLT将属性添加到标记

我还没有找到一个办法做到这一点

Svg为示例文档:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<svg xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" height="45" width="45" version="1.1" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/"> 
<g transform="matrix(1.25,0,0,-1.25,0,45)"> 
<path d="m9 18h18v-3h-18v3"/> 
</g> 
</svg> 

XSLT:

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' version='1.0'> 
<xsl:template match='path'> 
<xsl:copy> 
<xsl:attribute name='fill'>red</xsl:attribute> 
</xsl:copy> 
</xsl:template> 
</xsl:stylesheet> 

我需要做什么改变,使其添加/将填充属性更改为红色?

回答

3

我想你误解了XSLT是如何工作的。它需要一个输入XML树,并通过解释你的样式表来生成一个新的树。换句话说,您的样式表定义了如何根据输入XML树从头开始生成全新的树。

了解您不修改原始XML树很重要。这就像纯粹功能性和命令性语言之间的区别。底线:您不能更改fill属性为red,您可以生成fill属性设置为red的原始文档的副本。

这就是说,这是多还是少,你会怎么做:

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:svg="http://www.w3.org/2000/svg" version='1.0'> 
    <!-- this template is applied by default to all nodes and attributes --> 
    <xsl:template match="@*|node()"> 
     <!-- just copy all my attributes and child nodes, except if there's a better template for some of them --> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 

    <!-- this template is applied to an existing fill attribute --> 
    <xsl:template match="svg:path/@fill"> 
     <!-- produce a fill attribute with content "red" --> 
     <xsl:attribute name="fill">red</xsl:attribute> 
    </xsl:template> 

    <!-- this template is applied to a path node that doesn't have a fill attribute --> 
    <xsl:template match="svg:path[not(@fill)]"> 
     <!-- copy me and my attributes and my subnodes, applying templates as necessary, and add a fill attribute set to red --> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
      <xsl:attribute name="fill">red</xsl:attribute> 
     </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 
+0

感谢那些工作完美无瑕! – Peter 2012-03-03 18:03:06