xml - XSLT:更改某些属性值

标签 xml xslt xpath

我是 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/

相关文章:

java - XMLStreamReader 类中 getEventType() 方法的用途是什么

.net - 具有动态内容区域的 XSLT 布局

python - Elementtree 设置属性顺序

java - Spring xml 与 java 配置中的类类型注入(inject)

xslt - 如何计算xsl中相同的紧邻兄弟的数量

xml - 列出特定子元素的给定属性

c# - 如何转义经典 ASP 中的字符串以用于 XPath 查询?

c# - 使用 c#/htmlagilitpack 无法从 amazon.com 获取正确的信息

java - 一旦找到正确的对象,如何使@FindAll注释停止寻找对象?

html - XSLT 转换从混合内容中移除 HTML 元素