Convert Xml to DataTable

I have an XML file I want to insert that in a Datatable. The format of the xml file is like below:

<userid ID="37729">
  <TestId ID="84" TimeRemaining="60" />
  <QuestId ID="1">
    <Answer1>
    </Answer1>
    <Answer2>B</Answer2>
    <Answer3>
    </Answer3>
    <Answer4>
    </Answer4>
  </QuestId>
</userid>

Now I want to insert that in a data table like below:

Question Id     Answer1      Answer2        Answer3        Answer4
1                 A                                         D

2                             B              C     

3                                            C                     

Can any one help me to achieve this.


Solution 1:

I would first create a DataTable with the columns that you require, then populate it via Linq-to-XML.

You could use a Select query to create an object that represents each row, then use the standard approach for creating DataRows for each item ...

class Quest
{
    public string Answer1;
    public string Answer2;
    public string Answer3;
    public string Answer4;
}

public static void Main()
{
    var doc = XDocument.Load("filename.xml");

    var rows = doc.Descendants("QuestId").Select(el => new Quest
    {
        Answer1 = el.Element("Answer1").Value,
        Answer2 = el.Element("Answer2").Value,
        Answer3 = el.Element("Answer3").Value,
        Answer4 = el.Element("Answer4").Value,
    });

    // iterate over the rows and add to DataTable ...

}

Solution 2:

DataSet ds = new DataSet();
ds.ReadXml(fileNamePath);

Solution 3:

How To Read XML Data into a DataSet by Using Visual C# .NET contains some details. Basically, you can use the overloaded DataSet method ReadXml to get the data into a DataSet. Your XML data will be in the first DataTable there.

There is also a DataTable.ReadXml method.