简体   繁体   中英

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. 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. Perhaps I am adding the data incorrectly too. I know with PHP building strings in this fashion is less than optimal.

Here's a sample of the 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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