Question

I am trying to build an XML string from a CSV file in ASP.NET. I don't need the XML page to display necessarily because I'm building the XML string to then send to an API. The CSV is hosted on a server.

I need to be able to loop through the CSV until there is a blank row (the rows will vary as I use the CSV) and then stop the loop. It will go something like this (<Info> would be the content from the different rows in the CSV) :

<Example>
    <Info>
        <Name>This would be the name</Name>
        <Address>This would be the address</Address>
        <Email>This would be the email</Email>
    </Info>
    <Info>
        <Name>This would be the name</Name>
        <Address>This would be the address</Address>
        <Email>This would be the email</Email>
    </Info>
    <Info>
        <Name>This would be the name</Name>
        <Address>This would be the address</Address>
        <Email>This would be the email</Email>
    </Info>
</Example>

That's an example of how it would work if there were three rows in the CSV.

I saw this code here on Stack Overflow:

var lines = File.ReadAllLines("my_csv.csv");

var xml = new XElement("TopElement",
   lines.Select(line => new XElement("Item",
      line.Split(';')
      .Select((column, index) => new XElement("Column" + index, column)))));

xml.Save("my_csv.csv");

And I tried that (substituting my csv file name and path in) and that page wouldn't load.

Any ideas on what I'm doing wrong? Thank you.

Was it helpful?

Solution

You can easily build this using a simple StringBuilder. One example would be:

void Main()
{
     StringBuilder sb = new StringBuilder();
     sb.Append("<Example>");

    foreach(var line in File.ReadAllLines(@"c:\foo\line.csv"))
    {
      var row = line.Split(',');
      if(row.Length>=3)
      {
        sb.Append("<Info>");
        sb.Append("<Name>"+row[0]+"</Name>");
        sb.Append("<Address>"+row[1]+"</Address>");
        sb.Append("<Email>"+row[2]+"</Email>");
        sb.Append("</Info>");
      }
      else//assume blank row. Break out of loop
         break;
   }
   sb.Append("</Example>"); 

   //sb.ToString() has the piece of XML you want.
}

Another alternative would be to use an XMLSerializer, but producing the output exactly the same way you want/need it may not be as simple.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top