xslt - 具有 XPath 的唯一 ID 和多个类

标签 xslt class xpath replace unique

我正在使用 XSLT 来显示包含 liaul 菜单。

我想要以下:

  1. 找到第一个 li a 元素并添加 .firstitem 类。
  2. 找到最后一个 li a 元素并添加 .lastitem 类。
  3. 找到事件的 li a 元素并添加 .active 类。
  4. 为每个 li a 元素添加一个唯一的 ID。 (即 URL 友好的菜单文本作为 ID)。

我已成功完成第 1-3 步。除了当我尝试添加类时,它实际上替换了其他类而不是添加到它们中。

代码如下:

<li>
    <a>
        <!-- Add .firstitem class -->
        <xsl:if test="position() = 1">
            <xsl:attribute name="class">firstitem</xsl:attribute>
        </xsl:if>

        <!-- Add .lastitem class -->
        <xsl:if test="postition() = count(//Page)">
            <xsl:attribute name="class">lastitem</xsl:attribute>
        </xsl:if>

        <!-- Add .active class -->
        <xsl:if test="@Active='True'">
            <xsl:attribute name="class">active</xsl:attribute>
        </xsl:if>

        <!-- Add link URL -->
        <xsl:attribute name="href"><xsl:value-of select="@FriendlyHref" disable-output-escaping="yes"/></xsl:attribute>

        <!-- Add link text -->
        <xsl:value-of select="@MenuText" disable-output-escaping="yes"/>
    </a>
</li>

实际上,a 元素可以包含所有这三个类。但正如通过代码一样,它会替换 class 属性中的所有内容。如何添加类而不是替换它们?

我列表中的第 4 步是获取唯一 ID,最好基于 @MenuText。我知道有一个 replace() 函数,但我无法让它工作,我的编辑器说 replace() 不是一个函数。

菜单项文本包含在 id 属性中无效的空格、破折号和其他符号。如何替换这些符号?

最佳答案

<a>
       <xsl:attribute name="class">
            <!-- Add .firstitem class -->
            <xsl:if test="position() = 1">
                <xsl:text> firstitem</xsl:text>
            </xsl:if>
            <!-- Add .lastitem class -->
            <xsl:if test="postition() = count(//Page)">
                <xsl:text> lastitem</xsl:text>
            </xsl:if>

            <!-- Add .active class -->
            <xsl:if test="@Active='True'">
                <xsl:text> active</xsl:text>
           </xsl:if>
       </xsl:attribute>

        <!-- Add link URL -->
        <xsl:attribute name="href"><xsl:value-of select="@FriendlyHref" disable-output-escaping="yes"/></xsl:attribute>

        <!-- Add link text -->
        <xsl:value-of select="@MenuText" disable-output-escaping="yes"/>
    </a>

replace() 是一个 XSLT2.0 函数。使用 XSLT1.0 时,您需要一个 custom template进行大多数字符串操作。

关于xslt - 具有 XPath 的唯一 ID 和多个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2048546/

相关文章:

xml - 使用 ApacheFOP 在 Java 中从 XML 生成 PDF

xslt - XPath 通过命名空间从同级中获取值(value)

selenium - Selenium xpath即使在firepath中也可以工作,但没有此类元素异常

Perl Xpath : search item before a date year

c# - 即使存在命名空间也能工作的表达式?

javascript - 将javascript变量放入xsl属性

xslt - 在 xpath 中连接两个字符串序列

c++ - 在 ')' token 之前应为 '*'

powershell - 为什么 PowerShell [TYPE]::new() 是小写

python - 在 pygame 中执行 for 循环后,图像不会保留在屏幕上