我有一个 xml 文件,其结构如下所示:
<root>
<includes>
<includeFile name="../other/some_xml.xml"/>
</includes>
<itemlist>
<item id="1" >
<selections>
<selection name="one" />
</selections>
</item>
</itemlist>
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>
我创建了一个 XSLT,用它来过滤掉项目。问题是,对于每个文件,我必须检查它是否包含 includefile 标签,这是指向类似 xml 的相对路径,如果包含,我还需要从该文件中收集项目,递归地强>。现在我使用 xslt 转换了 xml,然后我必须解析 xml 以查找 includefile 标记。这个解决方案看起来并不优雅,我想知道是否所有这些都可以通过 xslt 完成。
最佳答案
XSLT document
XSLT 1.0 和 XSLT 2.0 中的函数另外还有 doc
功能允许您提取更多文档,然后可以使用匹配的模板进行处理。因此考虑移动您的 XSLT 编码风格来编写匹配模板和 apply-template,那么您就可以轻松做到
<xsl:template match="includes/includeFile">
<xsl:apply-templates select="document(@name)/*"/>
<xsl:template>
然后您只需确保 <xsl:template match="root">...</xsl:template>
创建您想要的输出。
关于java - 使用 XSLT 递归加载相关 XML 文件并应用转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28747484/