【问题标题】:XSLT mapping for selective xml attribute选择性 xml 属性的 XSLT 映射
【发布时间】:2021-02-24 10:12:03
【问题描述】:

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

有没有办法通过不触及其他属性来优化这一点,比如只将逻辑 customerDetails 写入 XSLT 中的 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>

【问题讨论】:

    标签: xml xslt xslt-1.0 xslt-2.0


    【解决方案1】:

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

    【讨论】:

    • 这真的很有帮助。
    猜你喜欢
    • 2018-09-15
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 2017-08-09
    相关资源
    最近更新 更多