gpt4 book ai didi

xml - 使用 XSLT 反转数据和属性

转载 作者:行者123 更新时间:2023-12-04 06:27:38 25 4
gpt4 key购买 nike

使用 XSLT 我想转换这个 XML:

<exchangeRates>
<rate country="aud">0.97</rate>
</exchangeRates>

进入这个 XML:
<xchgRates>
<entry xrate="0.97">aud</entry>
</xchgRates>

编辑:exchangeRates 需要变成 xchgRates。将 xRate 更改为 xrate 以匹配正确的解决方案。

感谢您的帮助!

最佳答案

完整而简短的解决方案 :

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>


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

<xsl:template match="exchangeRates">
<xchgRates>
<xsl:apply-templates select="node()|@*"/>
</xchgRates>
</xsl:template>

<xsl:template match="rate">
<entry xrate="{.}">
<xsl:value-of select="@country"/>
</entry>
</xsl:template>
</xsl:stylesheet>

当此转换应用于提供的 XML 文档时:
<exchangeRates>
<rate country="aud">0.97</rate>
</exchangeRates>

产生了想要的、正确的结果 :
<xchgRates>
<entry xrate="0.97">aud</entry>
</xchgRates>

说明 :
  • 使用和覆盖身份规则 /模板
  • 使用 AVT ( Attribute-Value-Templates ) 是推荐的,因为它需要更少的输入并产生更短、更易于理解和可维护的代码。

  • 除了少数异常(exception)(特别是 select 属性),几乎所有 XSLT 指令的属性都允许 AVT。

    关于xml - 使用 XSLT 反转数据和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5850005/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com