我是一个XSLT新手,有一个简单的任务:
假设我有以下XML:
Run Code Online (Sandbox Code Playgroud)<Element1> <Element2 attr1="1"/> </Element1> <Element1 attr1="2"/> <Element1> <Element2 attr1="2"/> </Element1>
我希望通过一次更改将XML转换为相同的XML:所有名为"attr1"的属性,无论它们在何处都必须进行转换,例如"1"将为"A"而"2"将为"X" ,即
Run Code Online (Sandbox Code Playgroud)<Element1> <Element2 attr1="A"/> </Element1> <Element1 attr1="X"/> <Element1> <Element2 attr1="X"/> </Element1>
我怎样才能做到这一点?提前致谢!
您可以定义要替换和替换字符的字符,然后使用translate.你可以使用这个XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
<xsl:output method="xml" indent="yes"/>
<xsl:variable name="in">12</xsl:variable>
<xsl:variable name="out">AX</xsl:variable>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@attr1">
<xsl:attribute name="attr1">
<xsl:value-of select="translate(., $in, $out)"/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
其他方式:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@attr1">
<xsl:choose>
<xsl:when test=". = '1'">
<xsl:attribute name="attr1">
<xsl:text>A</xsl:text>
</xsl:attribute>
</xsl:when>
<xsl:when test=". = '2'">
<xsl:attribute name="attr1">
<xsl:text>X</xsl:text>
</xsl:attribute>
</xsl:when>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
<xsl:template match="@attr1">将匹配所有属性attr1,然后使用xsl:choose您为此属性创建适当的值.
您没有说出@ attr = 3时会发生什么,所以如果它不是所选的那个,那么只有复制该值的else子句.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@attr1">
<xsl:attribute name="attr1">
<xsl:choose>
<xsl:when test=". = 1">
<xsl:text>A</xsl:text>
</xsl:when>
<xsl:when test=". = 2">
<xsl:text>X</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="." />
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)