Dynamically include XML files using XSLT

无人久伴 提交于 2019-12-12 02:56:00

问题


I am trying to merge multiple XML files into one in the following manner:

Say I have an XML file, called fruit.xml:

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

and subsequent XML files that are referenced from fruit.xml, like for example apples.xml:

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

and so on... I would like to merge these into 1 XML file, like such:

<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>

I want to determine the "child" files (like apples.xml, bananas.xml, etc.) dynamically based on the values of the ref attributes in the <include> elements of fruits.xml and then include them in the output.

Is this possible using XSLT?


回答1:


If only the contend of an file should be included you can use:

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

Therefore try this:

<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>


来源:https://stackoverflow.com/questions/16671472/dynamically-include-xml-files-using-xslt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!