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

时间:2013-10-10 16:20:25

标签: c# xml csv header

将通用xml构建到csv转换器作为项目来帮助学习c#,并且正在寻找一种将标题行插入CSV的优雅方法。我可以在循环中手动构建它,就像我通过用逗号附加节点名来附加XML数据值一样,但似乎应该有一种更有效的方法将doc.Descendants集合转换为逗号分隔列表。也许我也错误地添加了数据。我知道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();
}

1 个答案:

答案 0 :(得分:0)

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