【问题标题】:Using param values as position使用参数值作为位置
【发布时间】:2013-12-17 13:42:27
【问题描述】:

我有几个 XML 文档,每个文档都是一本书的一个章节。所有这些文件都合并到一个 DOMDocument 中,其中将 <book> 添加为根元素。

DOMDocument 得到以下结构:

<book>
<chapter title="This is the first chapter">
    <section title="This is the first section">
    <paragraph title="This is the first paragraph">This is the paragraph content</paragraph>
    </section>
    </chapter>
<chapter title="This is the second chapter">
    <section title="This is the first section">
    <paragraph title="This is the first paragraph">This is the paragraph content</paragraph>
    </section>
    </chapter>
</book>

我成功地制作了一个目录,我可以在其中选择带有查询字符串链接的章节(即 default.php?chapter=1)。当我尝试打开一章时,参数“chapter”被设置为查询字符串。

如何才能成功显示与查询字符串相等的章节?我从参数设置位置时遇到问题。我收到“未定义的变量”错误。但是当我在 value-of 中使用它时没有错误。

<xsl:param name="chapter" />

    <xsl:template match="//chapter[$chapter]">
            <html>
            <head>
                <title><xsl:value-of select="$chapter"/> - <xsl:value-of select="@title"/></title>
            </head>
            <body>              
        <h1>
            Chapter <xsl:value-of select="$chapter"/> <xsl:value-of select="@title"/>
        </h1>
        <xsl:apply-templates />
            </body>
        </html>
    </xsl:template>

所以,我想要的是,当用户访问“default.php?chapter=1”时,他会得到唯一的第 1 章:

<html>
<head>
<title>Chapter 1 - This is chapter 1</title>
</head>
<body>
<h1>Chapter 1 - This is chapter 1</h1>
blablablablablablabla
</body>
</html>

【问题讨论】:

  • 你不能在
  • 我用我想要的结果更新了我的问题。我只想根据查询字符串显示 1 章。

标签: xml xslt


【解决方案1】:

如果将此 XSLT 应用于源 XML:

<xsl:param name="chosenChapter" select="'1'"/>

<xsl:template match="/">
    <list>
        <xsl:apply-templates select="book/chapter[position() = $chosenChapter]"/>
    </list>
</xsl:template>


<xsl:template match="chapter">
    <xsl:param name="chapter" select="@title"/>
    
    
    <html>
        <head>
            <title><xsl:value-of select="$chosenChapter"/> - <xsl:value-of select="$chapter"/></title>
        </head>
        <body>              
            <h1>
                Chapter <xsl:value-of select="$chosenChapter"/> <xsl:value-of select="$chapter"/>
            </h1>
            <text>
                <xsl:apply-templates />
            </text>
        </body>
    </html>
</xsl:template>

样式表>

你得到这个输出:

<?xml version="1.0" encoding="UTF-8"?>
<list>
    <html>
            <head>
                    <title>1 - This is the first chapter</title>
            </head>
            <body>
                    <h1> Chapter 1This is the first chapter</h1>
                    <text> This is the paragraph content </text>
            </body>
    </html>
</list>

我编辑了我的问题。我希望这有帮助。在&lt;xsl:template match="" 中不能添加变量,但可以在&lt;xsl:apply-templates select="" 中。在我的示例中,chosenChapter 被硬编码为“1”。

【讨论】:

    猜你喜欢
    • 2019-03-29
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多