【问题标题】:xslt to transform the xml nodes dynamicallyxslt 动态转换 xml 节点
【发布时间】:2020-06-01 22:26:54
【问题描述】:

我正在努力根据键值动态更改我的 xml 的节点,下面是我的原始 xml,接下来是我想要在 xsl 转换后成为的 xml。

原始xml:

<Refd>
  <randr>

  <KeyPair>
  <Key>CM_001</Key>
  <Value>sometext</Value>
  </KeyPair>

  <KeyPair>
  <Key>CM_002</Key>
  <Value>sometext/Value>
  </KeyPair>

  <KeyPair>
  <Key>CM_003</Key>
  <Value>sometext/Value>
  </KeyPair>

  </randr>
  </Refd>

尝试如下:

  <Refd>
  <randr>

  <KeyPair_001>
  <Key>CM_001</Key>
  <Value>sometext</Value>
  </KeyPair_001>

  <KeyPair_002>
  <Key>CM_002</Key>
  <Value>sometext/Value>
  </KeyPair_002>

  <KeyPair_003>
  <Key>CM_003</Key>
  <Value>sometext/Value>
  </KeyPair_003>

  </randr>
  </Refd>

试图通过以下方式让 xslt 工作,但它只能让我获得 1 个标签,而其他标签保持不变,我可以让它为多个标签工作。提前谢谢你

  <xsl:template match="Refd/randr/KeyPair">
    <xsl:variable name="ename">
      <xsl:text>Key</xsl:text>
      <xsl:if test="Key ='CM_001'">
        <xsl:text>001</xsl:text>
      </xsl:if>
    </xsl:variable>
    <xsl:element name="{$ename}">
      <xsl:copy-of select="@*"/>
      <xsl:apply-templates select="node()"/>
    </xsl:element>
  </xsl:template>

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

    怎么样:

    XSLT 1.0

    <xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>
    
    <!-- identity transform -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="KeyPair">
        <xsl:element name="KeyPair{substring-after(Key, 'CM')}">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>
    
    </xsl:stylesheet>
    

    请注意,编号元素名称被认为是不好的做法。如果您的目标应用程序需要它,那么它是不可避免的;但一般来说,最好使用属性来实现此目的。

    【讨论】:

      猜你喜欢
      • 2011-07-20
      • 1970-01-01
      • 2011-02-10
      • 2017-07-20
      • 1970-01-01
      • 2014-07-16
      • 2019-04-26
      • 1970-01-01
      • 2019-08-03
      相关资源
      最近更新 更多