根据唯一元素值将XML文件拆分为多个文件

时间:2016-12-17 04:16:23

标签: xslt

我有一些XML,我需要根据标题的值将其拆分为多个XML。如果title具有相同的值,我需要分组并合并为一个XML 输入是。

我需要拆分以下XML文件

<Items>
  <Item>
    <Title>ABCD-1234-THND</Title>
    <DueDate>01-02-2008</DueDate>
  </Item>
  <Item>
    <Title>ABCD-1224-THND</Title>
    <DueDate>01-02-2009</DueDate>
  </Item>
  <Item>
    <Title>ABCD-1234-THND</Title>
    <DueDate>01-02-2010</DueDate>
  </Item>
  <Item>
    <Title>ABCD-1224-THND</Title>
    <DueDate>01-02-2011</DueDate>
  </Item>
  <Item>
    <Title>ABCD-1234-THND</Title>
    <DueDate>01-02-2012</DueDate>
  </Item>
  <Item>
    <Title> ABCD-1234-THND</Title>
    <DueDate>01-02-2013</DueDate>
  </Item>
  <Item>
    <Title>ABCD-1234-THND</Title>
    <DueDate>01-02-2013</DueDate>
  </Item>
</Items>

输出

<?xml version="1.0" encoding="UTF-8"?>
<Items>
  <Item>
    <Title>ABCD-1224-THND</Title>
    <DueDate>01-02-2011</DueDate>
  </Item>
  <Item>
    <Title>ABCD-1224-THND</Title>
    <DueDate>01-02-2011</DueDate>
  </Item>

</Items>

<?xml version="1.0" encoding="UTF-8"?>
<Items>
<Item>
    <Title>ABCD-1234-THND</Title>
    <DueDate>01-02-2008</DueDate>
  </Item>
  <Item>
<Item>
    <Title>ABCD-1234-THND</Title>
    <DueDate>01-02-2008</DueDate>
  </Item>
  <Item>
<Item>
    <Title>ABCD-1234-THND</Title>
    <DueDate>01-02-2008</DueDate>
  </Item>
  <Item>
<Item>
    <Title>ABCD-1234-THND</Title>
    <DueDate>01-02-2008</DueDate>
  </Item>
  <Item>
<Item>
    <Title>ABCD-1234-THND</Title>
    <DueDate>01-02-2008</DueDate>
  </Item>
  <Item>

</Items>

1 个答案:

答案 0 :(得分:1)

假设xslt 2可用,您可以使用result-document指定输出位置。

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/Items">
        <!-- Group Items by Title -->
        <xsl:for-each-group select="Item" group-by="Title">
            <!-- Write each group to a file with the title in the name -->
            <xsl:result-document href="items-{current-grouping-key()}.xml">
                <Items>
                    <xsl:copy-of select="current-group()"/>
                </Items>
            </xsl:result-document>
        </xsl:for-each-group>
    </xsl:template>
</xsl:stylesheet>