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

如何通过XSLT移除具有相同outputclass属性的首个title元素

处理重复outputclass="header"的title元素方案

看起来你需要处理XML中两个outputclass="header"的title元素,要求最终输出里<head>保留第一个这类标题,<body>保留第二个,同时保留章节标题和段落内容。我来给你一套可行的XSLT方案,分步骤解释:

先明确示例场景

假设你的输入XML是这样的(符合你说的两个outputclass="header"的title元素):

<document>
  <body>
    <title outputclass="header">文档主标题(首个)</title>
    <title outputclass="header">文档副标题(第二个)</title>
    <section>
      <title>第一章:入门指南</title>
      <p>这是章节里的第一段内容。</p>
    </section>
  </body>
</document>

你想要的预期输出是:

<document>
  <head>
    <title outputclass="header">文档主标题(首个)</title>
  </head>
  <body>
    <title outputclass="header">文档副标题(第二个)</title>
    <section>
      <title>第一章:入门指南</title>
      <p>这是章节里的第一段内容。</p>
    </section>
  </body>
</document>

对应的XSLT代码

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <!-- 身份模板:默认复制所有节点,确保非目标节点原样保留 -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <!-- 处理根节点document,专门处理header title的分配 -->
  <xsl:template match="document">
    <xsl:copy>
      <!-- 创建或复用head元素,放入第一个header title -->
      <head>
        <xsl:copy-of select="(//title[@outputclass='header'])[1]"/>
        <!-- 如果原head有其他内容,也一并保留 -->
        <xsl:apply-templates select="head/node()"/>
      </head>
      <!-- 处理body,传递参数标记要跳过第一个header title -->
      <xsl:apply-templates select="body">
        <xsl:with-param name="skip-first-header" select="true()"/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

  <!-- 处理body中的header title:跳过第一个,保留后续的 -->
  <xsl:template match="body/title[@outputclass='header']">
    <xsl:param name="skip-first-header"/>
    <!-- 只有当不是第一个header title时才复制 -->
    <xsl:if test="position() > 1">
      <xsl:copy-of select="."/>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

代码逻辑解释

  1. 身份模板:这是XSLT的基础,默认复制所有节点和属性,保证除了我们要特殊处理的header类型title,其他内容(比如章节标题、段落)都原样输出。
  2. document节点处理:在这里我们主动创建<head>元素,把XML中第一个outputclass="header"的title复制进去;同时给body的处理传递参数,告诉它要跳过第一个header title。
  3. body中的header title处理:专门匹配body里的header类型title,只保留位置大于1的(也就是第二个及以后的),第一个直接跳过不复制。

如果你的原XML已经有<head>元素,并且里面已经包含第一个header title,这段代码也能兼容——它会保留原head的内容,同时把第一个header title(不管原位置在哪)放进去,然后跳过body里的第一个header title。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 21:47:38