使用 XSLT 根据现有值更改属性值
问题描述:
我有一个如下的 XML 文档
I have an XML document as follows
<Element>
<Element1>
<Element2 attr1="Horizontal"/>
</Element1>
<Element1 attr1="V"/>
<Element1>
<Element2 attr1="Island"/>
</Element1>
</Element>
我想要一个 XSLT 来转换具有以下条件的 XML:
I would like to have an XSLT to transform the XML with the following conditions:
- 如果 attr1 值为 "Horizontal" 或 "H",则必须将其替换为 "H"
- 如果 attr1 的值为Vertical"或V",则必须将其替换为V"
- 如果 attr1 值为Island"或ISL",则必须将其替换为ISL"
- 否则 attr1 中的值将保持原样
使生成的 XML 显示如下:
So that the resultant XML appears as follows:
<Element>
<Element1>
<Element2 attr1="H"/>
</Element1>
<Element1 attr1="V"/>
<Element1>
<Element2 attr1="ISL"/>
</Element1>
</Element>
我有以下 XSLT.or 条件在这里似乎不起作用.我该如何更改?
I have the following XSLT. The or condition does not seem to work here. How can I change it?
<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=". ='Horizontal' or 'H'">
<xsl:text>H</xsl:text>
</xsl:when>
<xsl:when test=". = 'Vertical' or 'V'">
<xsl:text>V</xsl:text>
</xsl:when>
</xsl:choose>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
答
代替:
<xsl:when test=". ='Horizontal' or 'H'">
你应该使用:
<xsl:when test=". ='Horizontal' or . = 'H'">
或者干脆:
<xsl:when test=". ='Horizontal'>
因为你真的不想改变H".
since you don't really want to change "H".
这是一个完整的例子:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity 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=". = 'Horizontal'">H</xsl:when>
<xsl:when test=". = 'Vertical'">V</xsl:when>
<xsl:when test=". = 'Island'">ISL</xsl:when>
<xsl:otherwise>
<xsl:value-of select="."/>
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>