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

如何使用XSLT创建变量统计XML中ingredient元素总数?

解决方案

首先修复你的XML文件语法错误:第二个<pc:ingredient name="onion">未闭合,且原XML缺失pc命名空间的URI声明,这会导致XML解析失败,修正后的XML如下:

<?xml version="1.0" encoding="UTF-8"?>
<pc:recipe
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:pc="http://example.com/recipe"
    version="0.1">
    <pc:ingredient name="tomato">
    </pc:ingredient>
    <pc:ingredient name="onion">
    </pc:ingredient>
    <pc:ingredient name="paprika">
    </pc:ingredient>
</pc:recipe>

接下来修改XSLT文件,完成两个核心操作:

  • 声明与XML一致的pc命名空间
  • 用count()函数统计所有pc:ingredient元素的数量并存储到变量中

完整XSLT代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:pc="http://example.com/recipe">

<!-- 定义变量存储ingredient总数量 -->
<xsl:variable name="totalAmount" select="count(//pc:ingredient)" />

<!-- 示例:输出变量值验证结果 -->
<xsl:template match="/">
    <total-ingredients>
        <xsl:value-of select="$totalAmount" />
    </total-ingredients>
</xsl:template>

</xsl:stylesheet>

关键说明:

  • //pc:ingredient是XPath表达式,匹配整个XML文档中所有pc:ingredient元素
  • count()函数返回匹配到的元素总数,赋值给$totalAmount变量
  • 必须保证XSLT与XML中的pc命名空间URI完全一致,否则XPath无法定位目标元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 08:57:11