使用XSLT将一个XML文件拆分为多个文件

时间:2018-07-24 09:59:02

标签: xml xslt

我正在努力将XML文件拆分为多个XML文件。我需要将-emlement中具有相同status_ids的所有元素和属性放在单独的文件中,并以 status_id 作为文件名。

XML文件看起来像:

<some>
    <more status="1" att="q" status_id="111">
        <text>asdf</text>
    </more>
    <more status="2" att="c" status_id="111">
        <text>fdas</text>
    </more>
    <more status="2" att="a" status_id="111">
        <text>qwer</text>
    </more>

    <more status="1" att="w" status_id="222">
        <text>yxcv</text>
    </more>
    <more status="2" att="f" status_id="222">
        <text>vvbmn</text>
    </more>
    <more status="2" att="g" status_id="222">
        <text>fgjh</text>
    </more>
</some>

我想要什么: XML-File_111.xml

<some>
    <more status="1" att="q" status_id="111">
        <text>asdf</text>
    </more>
    <more status="2" att="c" status_id="111">
        <text>fdas</text>
    </more>
    <more status="2" att="a" status_id="111">
        <text>qwer</text>
    </more>
</some>

XML-File_222.xml

<some>
    <more status="1" att="w" status_id="222">
        <text>yxcv</text>
    </more>
    <more status="2" att="f" status_id="222">
        <text>vvbmn</text>
    </more>
    <more status="2" att="g" status_id="222">
        <text>fgjh</text>
    </more>
</some>

到目前为止,我的XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="2.0">
<xsl:template match="/test">
    <xsl:for-each select="test/some/more">
        <xsl:result-document method="xml" href="file_{@status_id}.xml">
            <root>
                <xsl:copy-of select="//more[type = current()/status_id]/@*"/>
                <elem>
                    <xsl:copy-of select="../@* | ." />
                </elem>
            </root>
        </xsl:result-document>
    </xsl:for-each>
</xsl:template>

但是我对此一无所知。我只有一个空的XML文件。所以我做错了什么,那又是什么?

1 个答案:

答案 0 :(得分:2)

Typical grouping problem:

<xsl:template match="some">
  <xsl:for-each-group select="more" group-by="@status_id">
    <xsl:result-document href="file_{current-grouping-key()}.xml">
       <some>
         <xsl:copy-of select="current-group()"/>
       </some>
    </xsl:result-document>
  </xsl:for-each-group>
</xsl:template>