【问题标题】:Dynamically include XML files using XSLT使用 XSLT 动态包含 XML 文件
【发布时间】:2013-05-16 07:21:55
【问题描述】:

我正在尝试通过以下方式将多个 XML 文件合并为一个:

假设我有一个 XML 文件,名为 fruit.xml

<fruit>
    <apples>
        <include ref="apples.xml" />
    </apples>
    <bananas>
        <include ref="bananas.xml" />
    </bananas>
    <oranges>
        <include ref="oranges.xml" />
    </oranges>
</fruit>

以及从fruit.xml 引用的后续XML 文件,例如apples.xml

<fruit>
    <apples>
        <apple type="jonagold" color="red" />
        <... />
    </apples>
</fruit>

等等...我想将它们合并到 1 个 XML 文件中,如下所示:

<fruit>
    <apples>
        <apple type="jonagold" color="red" />
        <... />
    </apples>
    <bananas>
        <banana type="chiquita" color="yellow" />
        <... />
    </bananas>
    <oranges>
        <orange type="some-orange-type" color="orange" />
        <... />
    </oranges>
</fruit>

我想根据fruits.xml&lt;include&gt; 元素中的ref 属性的值动态确定“子”文件(如apples.xmlbananas.xml 等),然后包含它们在输出中。

这是否可以使用 XSLT?

【问题讨论】:

    标签: xml xslt dynamic include


    【解决方案1】:

    如果只包含文件的内容,您可以使用:

    <xsl:copy-of select="document(@ref)/fruit/*/*"/>
    

    所以试试这个:

    <xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    
        <xsl:output indent="yes" method="xml" encoding="utf-8" omit-xml-declaration="yes" />
    
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template>
    
        <xsl:template match="include">
            <xsl:copy-of select="document(@ref)/fruit/*/*"/>
        </xsl:template>
    </xsl:stylesheet>
    

    【讨论】:

    • 非常感谢,它有效!我现在正试图让它处理后续文件中的&lt;include&gt; 元素,就像这样:&lt;xsl:copy&gt;&lt;xsl:apply-templates select="document(@name)/fruit/*/*/*"/&gt;&lt;/xsl:copy&gt; 而不是&lt;xsl:copy-of ... /&gt;,但结果是&lt;include&gt;&lt;include&gt;&lt;banana .../&gt;&lt;/include&gt;&lt;/include&gt;。有什么建议吗?
    • 取消,已经修复:我删除了&lt;template match="include"&gt; 中的&lt;copy&gt; 元素!
    • 如果您必须查看包含文件中的特定元素,您也许可以使用 applytemplates
    猜你喜欢
    • 2021-11-04
    • 2011-12-17
    • 2021-05-24
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    相关资源
    最近更新 更多