You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过XSLT根据roll元素的@more属性在指定student元素中添加<more>元素?

Got it, let's fix this XSLT to properly implement your three requirements. The key is to target the right <student> elements based on the @more attribute in preceding siblings' <roll> elements.

Here's a clean, working XSLT solution:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- Identity template: copies all existing content by default -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!-- Template to insert <more> in qualifying students -->
    <xsl:template match="student[
        <!-- Condition 2: Immediate next sibling of a student with roll@more='1' -->
        preceding-sibling::student[1]//roll[@more='1'] 
        or 
        <!-- Condition3: Any following sibling of a student with roll@more='2' -->
        preceding-sibling::student//roll[@more='2']
    ]">
        <xsl:copy>
            <more>Content here</more>
            <!-- Copy the rest of the student's content -->
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

How this works:

  1. Identity Template: This ensures every element, attribute, and text node is copied exactly as it appears in the input—we only override behavior where we need to add the <more> element.
  2. Qualifying Student Template: We target <student> elements that meet either of your two main conditions:
    • For @more="1": The student is the immediate next sibling (first following sibling) of a student containing a <roll> with @more='1'.
    • For @more="2": The student is any following sibling of a student containing a <roll> with @more='2' (so all students after that one get <more>).
  3. Requirement 1: If you need to add <more> to a specific hardcoded <student> (e.g., the first one), you can add an additional condition to the template match, like position() = 1 or use an ID attribute to target it directly.

Testing this with your input XML (where the first student has <roll more="1">), the output will have <more> only in the second student (matching requirement 2). If you change that attribute to more="2", both the second and third students will get <more> (matching requirement3).

Note: Your expected output shows <more> in both the second and third students, but that would only be correct if the <roll> had @more="2". The XSLT above strictly follows your stated requirements.

内容的提问来源于stack exchange,提问作者Kita Ansari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 20:08:11