我有这个源 xml 文件。
<DATA>
<DATASET>
<KE action="create">
<A>USVa</A>
<B>USVb</B>
<C>USV10</C>
</KE>
<KE>
....
</KE>
</DATASET>
</DATA>
元素“KE”大约出现了 30000 次。我想每 5000 个“KE”创建一个新的 XML 文件。在 30000 个 KE 元素的情况下,结果必须是 6 个单独的 xml 文件,并且结构是源 xml 的副本。
如何使用 XSLT 2.0 实现这一点?我正在使用 saxonhe9-5-1-3j。非常感谢...
最佳答案
使用 XSLT 2.0 功能 xsl:for-each-group
和 KE
元素位置的模数。然后,使用 xsl:result-document
元素生成输出文档。
我的示例 XSLT 代码为 3 个 KE
元素的组创建了一个新的结果文档。为您的输入 XML 将此数字调整为“5000”。
样式表
1 简化了样式表,感谢@Martin Honnen。 2 由@michael.hor257k 建议再次编辑。
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/DATA">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="DATASET">
<xsl:for-each-group select="KE" group-starting-with="KE[(position() -1)mod 3 = 0]">
<xsl:variable name="file" select="concat('ke',position(),'.xml')"/>
<xsl:result-document href="{$file}">
<DATA>
<DATASET>
<xsl:copy-of select="current-group()"/>
</DATASET>
</DATA>
</xsl:result-document>
</xsl:for-each-group>
</xsl:template>
</xsl:stylesheet>
您会得到以下输出(为了方便,我对 KE
元素进行了编号,样式表不依赖于 n
属性)。
输出:ke1.xml
<?xml version="1.0" encoding="UTF-8"?>
<DATA>
<DATASET>
<KE n="1" action="create">
<A>USVa</A>
<B>USVb</B>
<C>USV10</C>
</KE>
<KE n="2" action="create">
<A>USVa</A>
<B>USVb</B>
<C>USV10</C>
</KE>
<KE n="3" action="create">
<A>USVa</A>
<B>USVb</B>
<C>USV10</C>
</KE>
</DATASET>
</DATA>
输出:ke2.xml
<?xml version="1.0" encoding="UTF-8"?>
<DATA>
<DATASET>
<KE n="4" action="create">
<A>USVa</A>
<B>USVb</B>
<C>USV10</C>
</KE>
<KE n="5" action="create">
<A>USVa</A>
<B>USVb</B>
<C>USV10</C>
</KE>
<KE n="6" action="create">
<A>USVa</A>
<B>USVb</B>
<C>USV10</C>
</KE>
</DATASET>
</DATA>
其他输出文档看起来一样。
关于xml - 使用 xslt 2.0 拆分大型 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21131423/