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

XSLT 1.0如何匹配属性值并获取对应子元素?

解决方案:用XSLT 1.0的key实现作者信息匹配

在XSLT 1.0中处理跨节点的ID引用,最高效可靠的方式是使用<xsl:key>定义索引,再通过key()函数快速查找对应节点,比你之前尝试的if匹配更简洁准确。

核心步骤

  1. 定义索引键:针对authors下的author节点,用其id属性作为索引键值。
  2. 关联查找:在处理章节的模板中,通过章节的chapterAuthor/@author_id,调用key()函数匹配对应的作者节点,提取givenname值。

示例代码

原XML结构(参考)

<root>
  <authors>
    <author id="auth_001">
      <givenname>Alice</givenname>
      <surname>Brown</surname>
    </author>
    <author id="auth_002">
      <givenname>Bob</givenname>
      <surname>Wilson</surname>
    </author>
  </authors>
  <chapters>
    <chapter>
      <title>XSLT基础入门</title>
      <chapterAuthor author_id="auth_001"/>
    </chapter>
    <chapter>
      <title>高级节点处理</title>
      <chapterAuthor author_id="auth_002"/>
    </chapter>
  </chapters>
</root>

实现的XSLT代码

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <!-- 定义作者索引:用author的id属性作为查找键 -->
  <xsl:key name="author-index" match="author" use="@id"/>

  <!-- 根节点模板 -->
  <xsl:template match="/">
    <output>
      <xsl:apply-templates select="root/chapters/chapter"/>
    </output>
  </xsl:template>

  <!-- 章节处理模板 -->
  <xsl:template match="chapter">
    <content_item>
      <title><xsl:value-of select="title"/></title>
      <!-- 通过key函数匹配author_id对应的作者,提取givenname -->
      <given_name>
        <xsl:value-of select="key('author-index', chapterAuthor/@author_id)/givenname"/>
      </given_name>
    </content_item>
  </xsl:template>
</xsl:stylesheet>

多作者场景扩展

如果单个章节有多个chapterAuthor节点,只需新增chapterAuthor的处理模板即可:

<xsl:template match="chapter">
  <content_item>
    <title><xsl:value-of select="title"/></title>
    <authors_list>
      <xsl:apply-templates select="chapterAuthor"/>
    </authors_list>
  </content_item>
</xsl:template>

<xsl:template match="chapterAuthor">
  <given_name>
    <xsl:value-of select="key('author-index', @author_id)/givenname"/>
  </given_name>
</xsl:template>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:45:17