【问题标题】:How to split XML file into many XML files using XSLT如何使用 XSLT 将 XML 文件拆分为多个 XML 文件
【发布时间】:2011-01-28 21:47:36
【问题描述】:

我想知道如何编写 XSLT 根据这些要求将一个 XML 文件拆分为多个 XML 文件:

  • file1.xml - type= Natyral 的湖泊
  • file2.xml - type=Artificial 的湖
  • file3.xml - type=Glacial 的湖泊

XML 输入文件为:

<Lakes>
  <Lake>
    <id>1</id>
    <Name>Caspian</Name>
    <Type>Natyral</Type>
  </Lake>
  <Lake>
    <id>2</id>
    <Name>Moreo</Name>
    <Type>Glacial</Type>
  </Lake>
  <Lake>
    <id>3</id>
    <Name>Sina</Name>
    <Type>Artificial</Type>
  </Lake>
</Lakes>

【问题讨论】:

  • 如果效率很重要,vtd-xml是另一种选择,使用起来也很简单,但需要一些编码。

标签: xml xslt


【解决方案1】:

使用 XSLT 2.0,比如这个样式表:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <xsl:for-each-group select="Lakes/Lake" group-by="Type">
            <xsl:result-document href="file{position()}.xml">
                <Lakes>
                    <xsl:copy-of select="current-group()"/>
                </Lakes>
            </xsl:result-document>
        </xsl:for-each-group>
    </xsl:template>
</xsl:stylesheet>

注意xsl:result-document 指令。

【讨论】:

    【解决方案2】:

    使用标准 XSL,不可能有多个输出 xml(即结果树)。
    但是,使用 Xalan redirect 扩展,您可以。

    查看链接中页面上的示例。我用 Xalan Java 2.7.1 测试了以下内容

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:redirect="http://xml.apache.org/xalan/redirect" extension-element-prefixes="redirect">
    
        <xsl:output method="xml" indent="yes" />
    
        <xsl:template match="/">
            <xsl:apply-templates />
        </xsl:template>
    
        <xsl:template match="/Lakes/Lake[Type='Natyral']">
            <redirect:write file="/home/me/file1.xml">
                <NatyralLakes>
                    <xsl:copy-of select="." />
                </NatyralLakes>
            </redirect:write>
        </xsl:template>
    
        <xsl:template match="/Lakes/Lake[Type='Artificial']">
            <redirect:write file="/home/me/file1.xml">
                <ArtificialLakes>
                    <xsl:copy-of select="." />
                </ArtificialLakes>
            </redirect:write>
        </xsl:template>
    
        <xsl:template match="/Lakes/Lake[Type='Glacial']">
            <redirect:write file="/home/me/file3.xml">
                <GlacialLakes>
                    <xsl:copy-of select="." />
                </GlacialLakes>
            </redirect:write>
        </xsl:template>
    
    
    </xsl:stylesheet>
    

    【讨论】:

    • 在 XSLT 1.0 中这是不可能的……在 2.0 中非常有可能
    • 是的,我应该提到我在谈论 XSLT 1.0。由于 Xalan 确实/不会实现 xslt 2.0,所以我在我的 java 代码中坚持使用 1.0。我还可以提到 exslt document 扩展,它为 xslt 1.0 实现了类似的结果
    • 请不要将 XSLT 1.0 称为“标准 XSL”。很多人仍在使用它,但它不再是标准。
    猜你喜欢
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多