使用C#将XML转换为CSV时添加表头后数据丢失如何解决
问题原因
- 输出拼接逻辑错误:
File.WriteAllText中string.Join的参数使用错误,导致表头和数据行之间多插入了空行,同时数据行的拼接格式不符合预期。 - 每行数据末尾多拼接了多余逗号:遍历ColData时每次都在值后面加逗号,最终每行末尾多一个逗号,造成字段和表头错位匹配。
- 没有保证每行字段数和6个表头的数量一致,可能出现字段缺失问题。
修正后的代码
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; namespace myApp{ class WriteToCSVFile{ static void Main(String[] args){ string xml = File.ReadAllText("C:\\bartact_inventory.xml"); XDocument Xdoc = XDocument.Parse(xml); // 将表头作为第一行存入列表,后续统一拼接 List<string> csvAllLines = new List<string> { "Application/Fitment,Part#,Item Description,Vendor,QOH,Unit Of Measure" }; XElement xeQBXML = Xdoc.Element("QBXML"); XElement xeQBXMLMsgsRs = xeQBXML.Element("QBXMLMsgsRs"); XElement XDEGeneralSummaryReportQueryRs = xeQBXMLMsgsRs.Element("GeneralSummaryReportQueryRs"); XElement xeReportRet = XDEGeneralSummaryReportQueryRs.Element("ReportRet"); XElement xeReportData = xeReportRet.Element("ReportData"); List<XElement> xeDataRows = xeReportData.Elements("DataRow").ToList(); foreach (var xeData in xeDataRows) { XElement RowData = xeData.Elements("RowData").FirstOrDefault(); if(RowData == null) continue; string[] partIDs = RowData.Attribute("value")?.Value.Split(":") ?? Array.Empty<string>(); if(partIDs.Length == 2) { List<string> currentRowFields = new List<string> { partIDs[0], partIDs[1] }; // 按顺序收集列数据 List<XElement> xeColData = xeData.Elements("ColData").ToList(); foreach (var partAttributes in xeColData) { string value = partAttributes.Attribute("value")?.Value ?? ""; currentRowFields.Add(value); } // 保证字段数和表头一致,不足补空、超出截断 while(currentRowFields.Count < 6) { currentRowFields.Add(""); } csvAllLines.Add(string.Join(",", currentRowFields.Take(6))); } } // 统一拼接所有行输出 File.WriteAllText("C:\\bartact_inventoy1.csv", string.Join("\n", csvAllLines)); } } }
补充说明
如果XML中ColData的顺序和后四个表头(Item Description、Vendor、QOH、Unit Of Measure)的顺序不匹配,需要根据colID的对应关系手动调整字段顺序,不要直接按ColData的遍历顺序添加值。
内容的提问来源于stack exchange,提问作者Zeke Medina
相关产品推荐
相关产品推荐

