我是 XSLT 新手,有一个简单的任务:
假设我有以下 XML:
<Element1> <Element2 attr1="1"/> </Element1> <Element1 attr1="2"/> <Element1> <Element2 attr1="2"/> </Element1>
我想通过一次更改将 XML 转换为相同的 XML:所有名为“attr1”的属性,无论它们在哪里都必须转换,例如“1”将是“A”,“2”将是“X”,我。 e.到
<Element1> <Element2 attr1="A"/> </Element1> <Element1 attr1="X"/> <Element1> <Element2 attr1="X"/> </Element1>
我怎样才能做到这一点? 提前致谢!
最佳答案
可以定义字符替换和替换chars,然后使用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>
另一种方式:
<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>
<xsl:template match="@attr1">
将匹配所有属性 attr1
, 然后使用 xsl:choose
您为此属性创建了适当的值。
关于xml - XSLT:更改某些属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6787551/