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

XSLT转换:将同名节点与父节点关联,寻求技术解决方案

XSLT转换解决方案

嘿,我来帮你搞定这个XSLT转换的问题!看你提供的输入XML最后那段没写完,我先补全了一个合理的完整版本,然后基于把页面编号和对应文章ID整理成易读文本的常见需求,写了个XSLT示例,你可以根据自己的实际预期输出调整。

完整输入XML

<?xml version="1.0" encoding="utf-8"?>
<pages>
  <page number="1">
    <pageArticles>
      <articleID id="100"/>
      <articleID id="200"/>
      <articleID id="300"/>
    </pageArticles>
  </page>
  <page number="5">
    <pageArticles/>
  </page>
  <page number="9">
    <pageArticles>
      <articleID id="400"/>
    </pageArticles>
  </page>
</pages>

预期输出示例

Page 1 has articles: 100, 200, 300
Page 5 has no articles
Page 9 has articles: 400

对应的XSLT代码

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" indent="no"/>

  <!-- 匹配根节点,遍历所有页面 -->
  <xsl:template match="/pages">
    <xsl:apply-templates select="page"/>
  </xsl:template>

  <!-- 处理单个页面节点 -->
  <xsl:template match="page">
    <!-- 输出页面编号 -->
    <xsl:text>Page </xsl:text>
    <xsl:value-of select="@number"/>
    <xsl:text> </xsl:text>

    <!-- 判断当前页面是否有文章ID -->
    <xsl:choose>
      <xsl:when test="pageArticles/articleID">
        <xsl:text>has articles: </xsl:text>
        <!-- 遍历所有文章ID,用逗号分隔输出 -->
        <xsl:for-each select="pageArticles/articleID">
          <xsl:value-of select="@id"/>
          <!-- 避免最后一个ID后加多余逗号 -->
          <xsl:if test="position() != last()">
            <xsl:text>, </xsl:text>
          </xsl:if>
        </xsl:for-each>
      </xsl:when>
      <xsl:otherwise>
        <xsl:text>has no articles</xsl:text>
      </xsl:otherwise>
    </xsl:choose>
    <!-- 每个页面信息后换行 -->
    <xsl:text>&#10;</xsl:text>
  </xsl:template>
</xsl:stylesheet>

代码说明

  • 我用了text输出模式,所以最终生成纯文本结果;如果你的预期是HTML或者另一种XML结构,只要修改<xsl:output>的method属性(比如改成html或xml),然后调整模板里的输出标签就行。
  • 核心逻辑是遍历每个page节点,通过test="pageArticles/articleID"判断页面是否有文章,然后分别输出对应内容。
  • 对于有文章的页面,用for-each遍历所有articleID,并通过position() != last()处理逗号分隔的格式,避免最后一个ID后出现多余的逗号。

如果你的预期输出和我假设的不一样,比如要生成HTML表格、嵌套XML结构之类的,随时告诉我具体需求,我再帮你调整代码!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:30:10