我有一个以下格式的xml文档:
<xml>
<dtd name="formslst">
<XMLDOC>
<formslst>
<forms>
<h1>
Level 1 heading
<h2>
level 2 heading
<h3>
level 3 heading
<file>
file1.pdf
<title>
title of file 1
<file>
file2.pdf
<title>
title of file2
<h3> level 3 internal heading
<file> file2.pdf
<title>
title of file 3
</title>
</file>
</h3>
</title>
</file>
</title>
</file>
</h3>
</h2>
</h1>
</forms>
</formslst>
</XMLDOC>
我想要的是xslt脚本,这样如果我将参数作为“file2.pdf”传递,它应该返回file2.pdf的标题为“file2的标题”和前面的h3“ 3级标题“,h2”级别2标题“和h1”级别1标题“文本值。
但是如果我传递file3.pdf那么它应该返回file3.pdf的标题为“文件3的标题”和前面的h3“ 3级内部标题”,h2“2级标题“和h1”级别1标题“文本值。
答案 0 :(得分:0)
您可以通过执行以下操作来匹配相关文件(其中 $ file 是包含您的文件名的参数)
<xsl:apply-templates select="//file[normalize-space(text()) = $file]"/>
一旦文件匹配,就可以非常简单地获得标题
<xsl:value-of select="normalize-space(title/text())" />
通过查看xml的结构(由于缺少关闭 dtd 和 xml 标记而没有格式良好),您实际上并不希望在 h 元素之前,但是祖先
<xsl:apply-templates select="ancestor::h1|ancestor::h2|ancestor::h3">
这是完整的XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:param name="file" select="'file2.pdf'"/>
<xsl:template match="/">
<xsl:apply-templates select="//file[normalize-space(text()) = $file]"/>
</xsl:template>
<xsl:template match="file">
<title>
<xsl:value-of select="normalize-space(title/text())"/>
</title>
<xsl:apply-templates select="ancestor::h1|ancestor::h2|ancestor::h3">
<xsl:sort select="position()" order="descending"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="h1|h2|h3">
<xsl:copy>
<xsl:value-of select="normalize-space(text())"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
当应用于您的示例XML时,会返回以下内容(请注意,您的XML中有两个 file2.pdf ,我假设第二个应该是 file3.pdf
<title>title of file2</title>
<h3>level 3 heading</h3>
<h2>level 2 heading</h2>
<h1>Level 1 heading</h1>
当参数更改为 file3.pdf 时,输出如下:
<title>title of file 3</title>
<h3>level 3 internal heading</h3>
<h3>level 3 heading</h3>
<h2>level 2 heading</h2>
<h1>Level 1 heading</h1>