将具有SAME ID的多个节点合并为一个但附加所有CHILDS

时间:2011-09-13 16:56:08

标签: xml xslt xpath merge

如果有人可以帮我处理这段xmlt,那就太好了。

我想转换这个xml片段:

<root>
  <rowdata>
    <ID>1</ID>
    <pxPages>
      <rowdata>
        <comment>comment 1</comment>
      </rowdata>
    </pxPages>
  </rowdata>
  <rowdata>
    <ID>2</ID>
    <pxPages>
      <rowdata>
        <comment>comment 2</comment>
      </rowdata>
    </pxPages>
  </rowdata>
  <rowdata>
    <ID>2</ID>
    <pxPages>
      <rowdata>
        <comment>comment 3</comment>
      </rowdata>
    </pxPages>
  </rowdata>
</root>

进入

 <root>
<ResultOperationalStatusCategory>
    <identifier>1</identifier>
    <comment>comment 1</comment>
</ResultOperationalStatusCategory>
<ResultOperationalStatusCategory>
    <identifier>2</identifier>
    <comment>comment 2</comment>
    <comment>comment 3</comment>
</ResultOperationalStatusCategory>

谢谢!

1 个答案:

答案 0 :(得分:0)

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

  <xsl:key name="k" match="rowdata" use="ID"/>

  <xsl:template match="/root">
    <xsl:copy>
      <xsl:apply-templates select="rowdata[generate-id(.) = 
                           generate-id(key('k', ID))]"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="rowdata">
    <ResultOperationalStatusCategory>
      <identifier>
        <xsl:value-of select="ID"/>
      </identifier>
      <xsl:copy-of select="key('k', ID)//comment"/>
    </ResultOperationalStatusCategory>   
  </xsl:template>

</xsl:stylesheet>

输出:

<root>
  <ResultOperationalStatusCategory>
    <identifier>1</identifier>
    <comment>comment 1</comment>
  </ResultOperationalStatusCategory>
  <ResultOperationalStatusCategory>
    <identifier>2</identifier>
    <comment>comment 2</comment>
    <comment>comment 3</comment>
  </ResultOperationalStatusCategory>
</root>