我有几个 xml 文件,它们的名称存储在另一个 xml 文件中。
我想使用 xsl 来生成 xml 文件组合的摘要。我记得有一种方法可以使用 msxml 扩展(我正在使用 msxml)。
我知道我可以使用每个文件的内容,select="document(filename)"
但我不确定如何将所有这些文件合并为一个。
2008 年 10 月 21 日我应该提到我想对组合的 xml 进行进一步处理,因此仅从转换中输出它是不够的,我需要将它作为节点集存储在变量中。
这只是你可以做的一个小例子:
文件 1.xml:
<foo>
<bar>Text from file1</bar>
</foo>
文件 2.xml:
<foo>
<bar>Text from file2</bar>
</foo>
索引.xml:
<index>
<filename>file1.xml</filename>
<filename>file2.xml</filename>
总结.xsl:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">
<xsl:variable name="big-doc-rtf">
<xsl:for-each select="/index/filename">
<xsl:copy-of select="document(.)"/>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="big-doc" select="exsl:node-set($big-doc-rtf)"/>
<xsl:template match="/">
<xsl:element name="summary">
<xsl:apply-templates select="$big-doc/foo"/>
</xsl:element>
</xsl:template>
<xsl:template match="foo">
<xsl:element name="text">
<xsl:value-of select="bar"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
将样式表应用于index.xml可为您提供:
<?xml version="1.0" encoding="UTF-8"?><summary><text>Text from file1</text><text>Text from file2</text></summary>
诀窍是使用文档函数(几乎所有 XSLT 1.0 处理器都支持的扩展函数)加载不同的文档,将内容作为变量主体的一部分输出,然后将变量转换为节点集以进行进一步处理。
假设您在这样的文件中列出了文件名:
<files>
<file>a.xml</file>
<file>b.xml</file>
</files>
然后你可以在上面的文件中使用这样的样式表:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<root>
<xsl:apply-templates select="files/file"/>
</root>
</xsl:template>
<xsl:template match="file">
<xsl:copy-of select="document(.)"/>
</xsl:template>
</xsl:stylesheet>
您可以document()
在转换过程中使用它来加载更多的 XML 文档。它们作为节点集加载。这意味着您最初将包含要加载到 XSLT 的文件名的 XML 提供给 XSLT,然后从那里获取它:
<xsl:copy-of select="document(@href)/"/>
感谢所有的答案。这是我与 msxml 一起使用的解决方案的要点。
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ms="urn:schemas-microsoft-com:xslt">
<xsl:output method="xml"/>
<xsl:template match="/">
<xsl:variable name="combined">
<xsl:apply-templates select="files"/>
</xsl:variable>
<xsl:copy-of select="ms:node-set($combined)"/>
</xsl:template>
<xsl:template match="files">
<multifile>
<xsl:apply-templates select="file"/>
</multifile>
</xsl:template>
<xsl:template match="file">
<xsl:copy-of select="document(@name)"/>
</xsl:template>
</xsl:stylesheet>
现在我正在尝试提高性能,因为每个文件大约 8 MB 并且转换需要很长时间,但这是另一个问题。