我有一个问题。我有一个 xml 文件如下:
Main.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<msrsw>
<software>
<chapter>
<name> Hello world</sample>
<xref type="xml">C:\ABC\NestedXML.xml</xref>
</chapter>
</software>
</msrsw>
NestedXml.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<msrsw>
<software>
<chapter>
<name> Nested XML </sample>
<age>14</age>
<country>Canada</country>
</chapter>
</software>
</msrsw>
我正在使用 Apache FOP 生成 PDF 文档(使用 Java)。 FOP 需要 src 和 dest 参数。 Src 为 Main.xml。 我的 XSLT 如下:
<xsl:param name="xmlFileName" />
<xsl:param name="XMLFile" select="document($xmlFileName)"/>
<xsl:template name="Chapters_1_2_Template">
<xsl:apply-templates select="$XMLFile/*" mode="chapter" />
</xsl:template>
<xsl:template match="node()" mode="chapter">
<xsl:for-each select="node()">
<xsl:if test="current()[name() = 'xref']">
<xsl:apply-templates select="current()[name() = 'xref']" mode="x" />
</xsl:if>
<xsl:if test="current()[name() = 'name']">
<xsl:apply-templates select="current()[name() = 'name']" mode="name" />
</xsl:if>
<xsl:if test="current()[name() = 'age']">
<xsl:apply-templates select="current()[name() = 'age']" mode="age" />
</xsl:if>
</xsl:for-each>
</xsl:template>
<xsl:template match="name" mode="name">
<xsl:value-of select="current()" />
</xsl:template>
<xsl:template match="age" mode="age">
<xsl:value-of select="current()" />
</xsl:template>
<xsl:template match="country" mode="country">
<xsl:value-of select="current()" />
</xsl:template>
<xsl:template match="xref" mode="x">
<xsl:param name="XMLFile" select="document(current())"/>
<xsl:call-template name="Chapters_1_2_Template" />
</xsl:template>
当我执行上述代码时,我在 <xsl:apply-templates select="$XMLFile/*" mode="chapter" />
行中收到以下错误:
Invalid token XMLFile.
当我删除 $XMLFile - <xsl:apply-templates select="*" mode="chapter" />
时,它对我来说可以很好地处理 Main.xml 文件的内容。
当我只在外部参照模板中显示 current() 的值时,它会解析 NestedXml.xml 文件并在 PDF 中显示字符串值。
预期输出为:
Hello world
Nested XML
14
Canada
我的要求是将 NestedXML.xml 的节点集嵌入 <xref></xref>
中标签并在该节点集上递归地应用模板。
但 document() 函数为我提供了 NestedXml.xml 的已解析字符串内容。
我不想使用 document() 函数,只想获取 NestedXml.xml 的字符串值。我需要使用相同的 XSLT 解析 NestedXml.xml 的所有标签。
请建议我哪里出错了。这种做法对吗?还有其他方法可以做到这一点吗?
或者使用 XSLT 无法以这种方式执行操作,并且 XSLT 允许仅包含已解析的字符串值?
最佳答案
如果您只需要一些文本节点,则样式表不必那么复杂。尝试这个更简单的样式表:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="text" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:apply-templates select="msrsw/software/chapter/name"/>
<xsl:apply-templates select="document(msrsw/software/chapter/xref)/*"/>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space()"/>
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>
关于java - 将嵌套 XML 文件解析为节点集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28260327/