简体   繁体   English

将xml转换为CSV时需要在csv中插入标头行

[英]Need to insert header row into csv when converting xml to CSV

Building a generic xml to csv converter as a project to help learn c# and am looking for an elegant way to insert the header row into the CSV. 构建一个通用的xml到csv转换器作为一个项目来帮助学习c#,并且正在寻找一种将标头行插入CSV的优雅方法。 I can build it in manually inside the loop the same way I am appending the XML data values by appending the node name with a comma but it seems like there should be a more efficient way to convert the doc.Descendants collection into a comma separated list. 我可以在循环内部手动构建它,就像通过在节点名称后添加逗号来添加XML数据值一样,但是似乎应该有一种更有效的方式将doc.Descendants集合转换为逗号分隔的列表。 Perhaps I am adding the data incorrectly too. 也许我也添加了错误的数据。 I know with PHP building strings in this fashion is less than optimal. 我知道以这种方式用PHP构建字符串并不是最佳选择。

Here's a sample of the XML: 这是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>

Here is the code: 这是代码:

//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();
}
String s=String.Join(",",doc.Descendants("fruit")
                            .Elements()
                            .Select(x=>x.Attribute("data").Value));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM