如何使用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
相关产品推荐
相关产品推荐

