将 xml 转换为 CSV 时需要将标题行插入 csv

本文关键字:标题 插入 csv xml 转换 CSV | 更新日期: 2023-09-27 18:34:51

构建一个通用的XML到csv转换器作为一个项目来帮助学习C#,并且正在寻找一种将标题行插入CSV的优雅方法。我可以在循环中手动构建它,就像我通过附加逗号的节点名称来附加 XML 数据值一样,但似乎应该有一种更有效的方法来转换文档。子体集合到逗号分隔的列表中。也许我也错误地添加了数据。我知道用这种方式构建PHP字符串不是最佳的。

下面是 XML 的示例:

<?xml version="1.0" ?>
<fruits>
  <fruit>
    <name data="watermelon" />
    <size data="large" />
    <color data="green" />
  </fruit>
  <fruit>
    <name data="Strawberry" />
    <size data="medium" />
    <color data="red" />
  </fruit>
</fruits>

这是代码:

//read the xml doc and remove BOM
string XML2Convert = System.IO.File.ReadAllText(@"C:'Websites'CSharp'Scripts'XML2CSVDocs'test.xml");
XML2Convert.Replace(((char)0xFEFF), ''0');
//parse into doc object
XDocument doc = XDocument.Parse(XML2Convert);
//create a new stringbuilder
StringBuilder sb = new StringBuilder(1000);
foreach (XElement node in doc.Descendants("fruit"))
{
  foreach (XElement innerNode in node.Elements())
  {
    //need a better way here to build the header row in the CSV
    //string headerRow = innerNode.Name + ",";
    //add the xml data values to the line
    //possibly a better way here also to add each value to the line
    sb.AppendFormat("{0}", innerNode.Attribute("data").Value + ",");
  }
  //remove trailing comma before appending the data line
  sb.Remove(sb.Length - 1, 1);
  //add a line to the stringBuilder object
  sb.AppendLine();
}

将 xml 转换为 CSV 时需要将标题行插入 csv

String s=String.Join(",",doc.Descendants("fruit")
                            .Elements()
                            .Select(x=>x.Attribute("data").Value));