使用 XSLT 根据现有值更改属性值 [英] Change attribute value based on existing value using XSLT

查看:32
本文介绍了使用 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:

  1. 如果 attr1 值为 "Horizo​​ntal" 或 "H",则必须将其替换为 "H"
  2. 如果 attr1 的值为Vertical"或V",则必须将其替换为V"
  3. 如果 attr1 值为Island"或ISL",则必须将其替换为ISL"
  4. 否则 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>

这篇关于使用 XSLT 根据现有值更改属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆