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

用XSLT为Adobe InDesign处理XML:按Cat分组并优化节点输出

解决方案:用XSLT按Cat字段分组,仅保留每组首个row的Cat节点

以下是实现需求的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>

    <!-- 定义分组键:以row节点下Cat的文本值作为分组依据 -->
    <xsl:key name="cat-group" match="row" use="Cat"/>

    <!-- 处理row节点的自定义规则 -->
    <xsl:template match="row">
        <xsl:copy>
            <!-- 仅保留当前Cat分组中第一个row的Cat节点 -->
            <xsl:if test="generate-id() = generate-id(key('cat-group', Cat)[1])">
                <xsl:apply-templates select="Cat"/>
            </xsl:if>
            <!-- 复制Title、Description、Price节点,不受分组影响 -->
            <xsl:apply-templates select="Title|Description|Price"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

代码说明

  • 默认模板:保证XML中除我们需要修改的部分外,其余结构和内容完全保留,无需额外编写复制逻辑。
  • 分组键cat-group:将所有row节点按Cat的文本值归类,相同分类的row会被分到同一组。
  • row节点处理:通过generate-id()判断当前row是否为所在分组的第一个节点,是则保留Cat,否则只保留其他内容节点。

输入XML

<Root>
  <row>
    <Cat>Cocktails</Cat>
    <Title>Virgin Berry Mojito</Title>
    <Description>Schweppes Russian Wild Berry, Beerenmix, Limette, Minze, Rohrzucker</Description>
    <Price>7,90</Price>
  </row>
  <row>
    <Cat>Cocktails</Cat>
    <Title>Sportsman</Title>
    <Description>Ananas, Orange, Zitrone, Grenadine</Description>
    <Price>7,90</Price>
  </row>
     <row>
    <Cat>Aperitifs</Cat>
    <Title>Lillet Wild Berry</Title>
    <Description>Lillet Blanc, Schweppes Russian Wild Berry</Description>
    <Price>7,90</Price>
  </row>
  <row>
    <Cat>Aperitifs</Cat>
    <Title>Aperol Spritz</Title>
    <Description>Prosecco, Aperol, Sodawasser</Description>
    <Price>7,90</Price>
    </row>
</Root>

期望输出XML

<Root>
  <row>
    <Cat>Cocktails</Cat>
    <Title>Virgin Berry Mojito</Title>
    <Description>Schweppes Russian Wild Berry, Beerenmix, Limette, Minze, Rohrzucker</Description>
    <Price>7,90</Price>
  </row>
  <row>
    <Title>Sportsman</Title>
    <Description>Ananas, Orange, Zitrone, Grenadine</Description>
    <Price>7,90</Price>
  </row>
  <row>
    <Cat>Aperitifs</Cat>
    <Title>Lillet Wild Berry</Title>
    <Description>Lillet Blanc, Schweppes Russian Wild Berry</Description>
    <Price>7,90</Price>
  </row>
  <row>
    <Title>Aperol Spritz</Title>
    <Description>Prosecco, Aperol, Sodawasser</Description>
    <Price>7,90</Price>
  </row>
</Root>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 08:45:07