我需要创建一个XSLT转换
输入
<pizza>
<pref name="cheese_cheddar" value="2" />
<pref name="meat_chicken" value="5" />
<pref name="cheese_edam" value="10" />
</pizza>输出
<pizza>
<pref name="cheese_cheddar" value="2" />
<pref name="tasty_cheese_cheddar" value="2" />
<pref name="meat_chicken" value="5" />
<pref name="cheese_edam" value="10" />
<pref name="tasty_cheese_edam" value="10" />
</pizza>也就是说,pizza中以cheese_开头的所有元素都需要复制,并修改name元素以附加到word tasty_。
我已经有了一个匹配程序,<xsl:template match="node()[starts-with(@name, 'cheese_')]">,但是我不知道如何复制元素和修改属性。我以前没有做过XSLT工作,所以我不确定copy和copy-to是否适合复制具有不同属性的元素。
发布于 2014-11-11 16:29:33
我自己回答这个问题,因为我从https://stackoverflow.com/a/17135323/255231得到了一个重要的线索
<?xml version="1.0" encoding="utf-8"?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="node()[starts-with(@name, 'cheese_')]">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:attribute name="name">tasty_<xsl:value-of select="@name"/></xsl:attribute>
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
</xsl:transform>发布于 2014-11-11 16:38:04
另一种选择:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="pref[starts-with(@name, 'cheese_')]">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
<xsl:element name="pref">
<xsl:attribute name="name">
<xsl:value-of select="concat('tasty_', @name)"/>
</xsl:attribute>
<xsl:attribute name="value">
<xsl:value-of select="@value"/>
</xsl:attribute>
</xsl:element>
</xsl:template>
</xsl:stylesheet>https://stackoverflow.com/questions/26869377
复制相似问题