使用XSLT合并具有公共子节点的两个节点

时间:2013-02-20 12:04:43

标签: xml xslt

我对XSLT一无所知,我需要快速解决这个问题:

我有一个像这样的xml结构:

<node>
    <sub_node_1> value_1 </sub_node_1>
    ...
    <sub_node_n> value_n </sub_node_n>
    <repeatable_node> another_value_1 </repeatable_node>
</node>
...
<node>
    <sub_node_1> value_1 </sub_node_1>
    ...
    <sub_node_n> value_n </sub_node_n>
    <repeatable_node> another_value_m </repeatable_node>
</node>

我希望在同一元素下聚合具有不同值的可重复节点,即类似这样的东西

<node>
    <sub_node_1> value_1 </sub_node_1>
    ...
    <sub_node_n> value_n </sub_node_n>
    <repeatable_node> another_value_1 </repeatable_node>
    ...
    <repeatable_node> another_value_m </repeatable_node>
</node>

1 个答案:

答案 0 :(得分:1)

这是一个简单的XSLT 1.0兼容解决方案:

样式表

<?xml version="1.0" encoding="iso-8859-1"?>

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

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

  <!-- Keep only the first <node> element -->
  <xsl:template match="node[1]">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
      <!-- Apply all repeatable_node children of following <node> siblings. -->
      <xsl:apply-templates select="following-sibling::node/repeatable_node"/>
    </xsl:copy>
  </xsl:template>

  <!-- Drop all <node> elements following the first <node> element -->
  <xsl:template match="node[position() &gt; 1]"/>

</xsl:stylesheet>

输入

<nodes>
  <node>
      <sub_node_1> value_1 </sub_node_1>
      <sub_node_n> value_n </sub_node_n>
      <repeatable_node> another_value_1 </repeatable_node>
  </node>
  <node>
      <sub_node_1> value_1 </sub_node_1>
      <sub_node_n> value_n </sub_node_n>
      <repeatable_node> another_value_m </repeatable_node>
  </node>
</nodes>

输出

<?xml version="1.0"?>
<nodes>
  <node>
    <sub_node_1> value_1 </sub_node_1>
    <sub_node_n> value_n </sub_node_n>
    <repeatable_node> another_value_1 </repeatable_node>
    <repeatable_node> another_value_m </repeatable_node>
  </node>
</nodes>