2014-03-13 40 views
1

我正在使用XSLT来复制文件,我想复制某个节点的所有属性,但我想用新的属性替换一些属性。例如,我可能会这样:是否有一种简单的方法来复制元素及其属性,同时只替换一些属性?

<Library> 
    <Book author="someone" pub-date="atime" color="black" pages="900"> 
    </Book> 
</Library> 

我怎么能复制这个,但用新值替换pub-date和color?有没有类似的东西?

<xsl:template match="/Library/Book"> 
    <xsl:copy> 
     <xsl:attribute name="pub-date">1-1-1976</xsl:attribute> 
     <xsl:attribute name="color">blue</xsl:attribute> 
     <xsl:apply-templates select="*@[not pub-date or color] | node()"/> 
    </xsl:copy> 
</xsl:template> 

但是,这不是有效的,当然...

+0

请不要在你的问题的标题包括“XSLT”。这是标签系统的用途。谢谢! –

回答

3

另一个方式是依靠这样一个事实,即如果相同的属性被写入两次,最后一个获胜。所以:

<xsl:template match="/Library/Book"> 
    <xsl:copy> 
     <xsl:copy-of select="@*"/> 
     <xsl:attribute name="pub-date">1-1-1976</xsl:attribute> 
     <xsl:attribute name="color">blue</xsl:attribute> 
     <xsl:apply-templates/> 
    </xsl:copy> 
</xsl:template> 

(你确实要使用模棱两可的日期格式1976年1月1日?)

+0

好点!但这仅仅是为了说明问题而设计的一个例子。 – nielsbot

3

我会开始像往常一样与身份转换模板

<xsl:template match="@* | node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@* | node()"/> 
    </xsl:copy> 
</xsl:template> 

然后添加

<xsl:template match="Book/@pub-date"> 
    <xsl:attribute name="pub-date">1-1-1976</xsl:attribute> 
</xsl:template> 

<xsl:template match="Book/@color"> 
    <xsl:attribute name="color">blue</xsl:attribute> 
</xsl:template> 
相关问题