简体   繁体   中英

Using XSLT to recursively load relative XML files and apply transformation

I have a xml file whose structure looks like this:

<root>
<includes>
    <includeFile name="../other/some_xml.xml"/>
</includes> 
<itemlist>  
        <item id="1" >
            <selections>
                <selection name="one" />
            </selections>
        </item>
</itemlist>

The xslt

    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xalan="http://xml.apache.org/xslt">
    <xsl:output method="xml" indent="yes" xalan:indent-amount="4" />

    <xsl:template match="/">
        <xsl:element name="ItemList">
            <xsl:if test="root/item">
                <xsl:call-template name="templ" />
            </xsl:if>
        </xsl:element>
    </xsl:template>

    <xsl:template name="templ">
        <xsl:element name="ItemList">
            <xsl:for-each select="root/itemlist/item">

                <xsl:element name="Item">
                    <xsl:element name="ItemIdentifier">
                        <xsl:value-of select="@id" />
                    </xsl:element>
                    <xsl:element name="Condition">
                        <xsl:value-of select="selections/selection[1]/@name" />
                    </xsl:element>
                </xsl:element>

            </xsl:for-each>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

I created one XSLT which i am using to filter out items. The problem is that for every file, i have to check if it contains the includefile tag, which is a relative path pointing to a similar xml, and if it does, i need to collect items from that file also, recursively . For now i transformed the xml using my xslt and then i have to parse the xml to look for includefile tag. This solution doesn't look elegant and i was wondering if all of it could be done via xslt.

The XSLT document function in XSLT 1.0 and in XSLT 2.0 additionally the doc function allow you to pull in further documents, processing is then simply possible with matching templates. So consider to move your XSLT coding style to write matching templates and apply-templates, then you can easily do

<xsl:template match="includes/includeFile">
  <xsl:apply-templates select="document(@name)/*"/>
<xsl:template>

and then you simply need to make sure the <xsl:template match="root">...</xsl:template> creates the output you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM