XSLT 1.0转换问题:将XML中<File>节点转为指定属性格式
XSLT 1.0 实现方案
输入XML示例
<Top> <XYZ> <File>/path/to/file1.txt</File> <File>/path/to/file2.txt</File> <File>/path/to/file3.txt</File> <File>/path/to/file4.txt</File> </XYZ> </Top>
正确的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" encoding="UTF-8"/> <xsl:template match="/"> <!-- 输出总文件数 --> <xsl:text>theFile.count=</xsl:text> <xsl:value-of select="count(/Top/XYZ/File)"/> <xsl:text> </xsl:text> <!-- 遍历输出每个文件路径 --> <xsl:for-each select="/Top/XYZ/File"> <xsl:text>theFile.</xsl:text> <xsl:value-of select="position()"/> <xsl:text>=</xsl:text> <xsl:value-of select="."/> <xsl:text> </xsl:text> </xsl:for-each> </xsl:template> </xsl:stylesheet>
关键说明
- 直接用
count(/Top/XYZ/File)获取<File>节点的总数量,这是解决你之前count输出1、2、3、4的核心——之前的错误应该是在循环里输出了每个节点的位置值,而非总数量。 - 指定
method="text"确保输出纯文本格式,符合你要的键值对样式。 - 通过
<xsl:for-each>遍历每个<File>,用position()获取节点索引,生成theFile.1到theFile.4的键名,同时输出对应的路径值。 是换行符,让输出每行一个键值对,结构更清晰。
输出结果
theFile.count=4 theFile.1=/path/to/file1.txt theFile.2=/path/to/file2.txt theFile.3=/path/to/file3.txt theFile.4=/path/to/file4.txt
内容的提问来源于stack exchange,提问作者Prashant2329
相关产品推荐
相关产品推荐

