Ritesh Naik
Ritesh Naik

Reputation: 21

Conversion of XML tags to CSV

I wants to convert some XML tags into Comma Separated Values (CSV)

    <variable name="Fault_Reset">
          <type>
            <BOOL />
          </type>
     </variable>
     <variable name="Cycle_On">
          <type>
            <BOOL />
          </type>
     </variable>

I want the output to look like this: variable name,type

e.g.

Fault_Reset,BOOL

Cycle_On,BOOL

Please help me out.

Upvotes: 0

Views: 140

Answers (1)

jdweng
jdweng

Reputation: 34421

like using Dictionaries for this type of code. I think the BOOL should be innertext instead of a tag name. Try code below which works with XML posted

using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication132
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, string> dict = doc.Descendants("variable")
                .GroupBy(x => (string)x.Attribute("name"), y => (string)y.Element("type").Elements().FirstOrDefault().Name.LocalName)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }
    }


}

Upvotes: 0

Related Questions