【问题标题】:Rename incremental node with fixed node value using xslt使用 xslt 重命名具有固定节点值的增量节点
【发布时间】:2017-02-09 23:15:15
【问题描述】:

我想使用 xslt 1.0 从我的输入 xml 获得以下输出。你能建议一种方法吗?

    Input xml:
    <result>
      <item0>
        <Name>Customer1</Name>
        <location>1360190</location>
      </item0>
     <item1>
       <Name>Customer2</Name>
      <location>1360190</location>
    </item1>
  </result>

     Output xml:
      <result>
        <item>
          <Name>Customer1</Name>
          <location>1360190</location>
        </item>
        <item>
          <Name>Customer2</Name>
          <location>1360190</location>
        </item>
      </result>

【问题讨论】:

  • 使用身份转换模板example,按原样复制所有节点。并添加另一个匹配/result/* 的模板,即result 的子元素,并根据需要对其进行转换。

标签: xml xslt xpath xslt-1.0


【解决方案1】:

正如@LingamurthyCS 提到的,考虑使用身份转换和模板重命名&lt;item&gt; 节点,并使用各种XPath 匹配 引用,如下所示:

在子元素上使用 result 引用和 apply-templates

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output version="1.0" encoding="UTF-8" indent="yes" method="xml"/>
<xsl:strip-space elements="*"/>

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

  <xsl:template match="result/*">
    <item>
      <xsl:apply-templates select="*"/>
    </item>
  </xsl:template>               

</xsl:transform>

在子元素上没有 result 引用和 copy-of

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output version="1.0" encoding="UTF-8" indent="yes" method="xml"/>
<xsl:strip-space elements="*"/>

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

  <xsl:template match="/*/*">
    <item>
      <xsl:copy-of select="*"/>
    </item>
  </xsl:template>               

</xsl:transform>

带有项目参考:

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output version="1.0" encoding="UTF-8" indent="yes" method="xml"/>
<xsl:strip-space elements="*"/>

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

  <xsl:template match="*[contains(name(), 'item')]">
    <item>
      <xsl:apply-templates />
    </item>
  </xsl:template>               

</xsl:transform>

【讨论】:

  • 太棒了!表示感谢的好方法是单击旁边的勾号以接受解决方案并确认您的问题已解决。
猜你喜欢
  • 1970-01-01
  • 2023-04-04
  • 2018-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
相关资源
最近更新 更多