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

PowerShell将CSV转换为单份指定格式XML文件的问题求助

你当前输出重复<Content>节点的原因是原有代码使用Group-Object CustomerNumber按客户编号分组后,在每个分组的遍历逻辑中都会完整渲染一次包含根节点的文档模板,导致每个客户都生成了一套完整的XML根结构,最终多个根节点被写入同一个文件。

修正后的完整代码

$docTemplate = @'
<Content>
      <Customers>
$($ctms -join "`n")
      </Customers>
  </Content>
'@

$entryTemplate = @'
          <Customer>
            <CustomerNumber>$($ctm.CustomerNumber)</CustomerNumber>
            <FirstName>$($ctm.FirstName)</FirstName>
            <LastName>$($ctm.LastName)</LastName>
            <Address_1>$($ctm.Address_1)</Address_1>
            <Address_2>$($ctm.Address_2)</Address_2>
            <Address_3>$($ctm.Address_3)</Address_3>
            <City>$($ctm.City)</City>
            <State>$($ctm.State)</State>
            <Zip>$($ctm.zip)</Zip>
          </Customer>
'@

# 直接遍历所有CSV记录,生成所有Customer节点
$ctms = foreach ($ctm in Import-Csv "sample.csv" -Delimiter ',') {
    $ExecutionContext.InvokeCommand.ExpandString($entryTemplate)  
}

# 仅渲染一次完整文档模板后输出到单个文件
$ExecutionContext.InvokeCommand.ExpandString($docTemplate) | Set-Content -LiteralPath 'sample.xml'

修改说明

  • 移除了不必要的分组逻辑,直接遍历所有CSV行批量生成所有<Customer>节点
  • 全局仅执行一次根文档模板渲染,保证输出的XML只有一个<Content>根节点
  • 直接指定固定输出文件名,符合单文件输出要求

内容的提问来源于stack exchange,提问作者Venkatesh Kopula Sivakumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 22:57:03