XSLT:更改某些属性值 [英] XSLT: Change certain attribute values

查看:37
本文介绍了XSLT:更改某些属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 XSLT 新手并且有一个简单的任务:

假设我有以下 XML:

<块引用>

<Element2 attr1="1"/><Element1 attr1="2"/><元素1><Element2 attr1="2"/>

我想通过一个更改将 XML 转换为相同的 XML:所有名为attr1"的属性无论在哪里都必须进行转换,例如1"将是A"而2"将是X",我.e.

<块引用>

<Element2 attr1="A"/><Element1 attr1="X"/><元素1><Element2 attr1="X"/>

我怎样才能做到这一点?提前致谢!

解决方案

例如,你没有说@attr=3 时会发生什么,所以有一个 else 子句,如果它不是选定的值之一,则只复制该值.

<xsl:template match="@*|node()"><xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy></xsl:模板><xsl:template match="@attr1"><xsl:attribute name="attr1"><xsl:when test=".=1"><xsl:text>A</xsl:text></xsl:when><xsl:when test=".=2"><xsl:text>X</xsl:text></xsl:when><xsl:否则><xsl:value-of select="."/></xsl:否则></xsl:选择></xsl:attribute></xsl:模板></xsl:stylesheet>

I am a XSLT newbie and have a simple task:

Suppose I have the following XML:

<Element1>
    <Element2 attr1="1"/>
</Element1>
<Element1 attr1="2"/>
<Element1>
    <Element2 attr1="2"/>
</Element1>

I want to transform the XML to the same XML with one change: All attributes named "attr1" no matter where they are have to be transformed so that for example "1" will be "A" and "2" will be "X", i. e. to

<Element1>
    <Element2 attr1="A"/>
</Element1>
<Element1 attr1="X"/>
<Element1>
    <Element2 attr1="X"/>
</Element1>

How can I achieve this? Thanks in advance!

解决方案

You didn't say what happens when @attr=3 for example so there is an otherwise clause to just copy the value if it is not one of the selected.

<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>

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

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