选择性 xml 属性的 XSLT 映射

XSLT mapping for selective xml attribute

我有一个用例,我只需要修改 XML 文件中的一个属性,而需要按原样保留其他段。在我的示例 XML 和构建的 XSLT 下方,我实际上是在尝试使用 XSLT 将“customerDetails”更改为“userDetails”,但我需要在 XSLT 中明确提及所有其他 XML 属性。

有没有一种方法可以优化这一点,比如只在 XSLT 中将逻辑 customerDetails 写入 userDetails,而不触及其他属性?

样本XML


    <?xml version="1.0" encoding="UTF-8"?>
    <RespData>
        <customerName>XXXX</customerName>
        <customerDetails>
            <customerId>123</customerId>
            <customerAddress>YYYY</customerAddress>
        </customerDetails>
    </RespData>

示例 XSLT


    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:template match="/">
            <RespData>
                <customerName>
                    <xsl:value-of select="/RespData/customerName" />
                </customerName>
                <xsl:for-each select="/RespData/customerDetails">
                    <userDetails>
                        <customerId>
                            <xsl:value-of select="customerId" />
                        </customerId>
                        <customerAddress>
                            <xsl:value-of select="customerAddress" />
                        </customerAddress>
                    </userDetails>
                </xsl:for-each>
            </RespData>
        </xsl:template>
    </xsl:stylesheet>

你根本没有任何属性,只有子元素;至于正确的方法,从身份转换开始,您可以使用顶级 <xsl:mode on-no-match="shallow-copy"/> 在 XSLT 3 中声明它,或者在 XSLT 1/2 中用

拼写出来
<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

然后为您需要的每个微更改添加模板,例如

<xsl:template match="customerDetails">
  <userDetails>
    <xsl:apply-templates/>
  </userDetails>
</xsl:template>