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

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>&#10;</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>&#10;</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的键名,同时输出对应的路径值。
  • &#10;是换行符,让输出每行一个键值对,结构更清晰。

输出结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 18:57:45