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

XSLT转换XML为带记录总数尾行的CSV报错求助

解决XML转带记录总数的CSV问题

1. 示例XML

<records>
  <record>
    <id>1</id>
    <name>Alice</name>
    <age>30</age>
  </record>
  <record>
    <id>2</id>
    <name>Bob Smith</name>
    <age>25</age>
  </record>
  <record>
    <id>3</id>
    <name>Charlie,Davis</name>
    <age>35</age>
  </record>
</records>

2. 修正后的XSLT代码

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="UTF-8"/>

  <!-- 处理字段中的逗号/引号,符合CSV规范 -->
  <xsl:template name="escape-csv">
    <xsl:param name="text"/>
    <xsl:choose>
      <xsl:when test="contains($text, ',') or contains($text, '&quot;')">
        <xsl:text>"</xsl:text>
        <xsl:value-of select="translate($text, '&quot;', '&quot;&quot;')"/>
        <xsl:text>"</xsl:text>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$text"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="/">
    <!-- 输出表头 -->
    <xsl:text>ID,Name,Age&#10;</xsl:text>
    
    <!-- 遍历输出每条记录 -->
    <xsl:for-each select="records/record">
      <xsl:call-template name="escape-csv">
        <xsl:with-param name="text" select="id"/>
      </xsl:call-template>
      <xsl:text>,</xsl:text>
      <xsl:call-template name="escape-csv">
        <xsl:with-param name="text" select="name"/>
      </xsl:call-template>
      <xsl:text>,</xsl:text>
      <xsl:call-template name="escape-csv">
        <xsl:with-param name="text" select="age"/>
      </xsl:call-template>
      <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
    
    <!-- 输出记录总数行 -->
    <xsl:text>Total Records:,</xsl:text>
    <xsl:value-of select="count(records/record)"/>
  </xsl:template>
</xsl:stylesheet>

3. 预期CSV输出

ID,Name,Age
1,Alice,30
2,Bob Smith,25
3,"Charlie,Davis",35
Total Records:,3

常见报错修复要点

  • 特殊字符破坏CSV结构:原代码若未处理字段中的逗号、引号,会导致CSV格式混乱,上述escape-csv模板按RFC 4180规范处理了这类情况。
  • 计数路径错误:如果你的XML包含命名空间,需在XSLT中声明命名空间前缀,比如XML是<ns:records>,则XSLT要添加xmlns:ns="http://你的命名空间地址",计数时使用count(ns:records/ns:record)。
  • 换行符跨平台问题:用&#10;表示换行,避免硬编码换行导致的Windows/Linux兼容性问题。
  • 编码乱码:通过encoding="UTF-8"指定输出编码,避免字符显示异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 01:06:20