Using XSLT to recursively load relative XML files and apply transformation

和自甴很熟 提交于 2019-12-11 06:29:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28747484/using-xslt-to-recursively-load-relative-xml-files-and-apply-transformation

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