Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 878
Vijjendra Avatar asked Jun 03 '11 14:06

Vijjendra


2 Answers

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 ...

}
like image 75
ColinE Avatar answered Sep 30 '22 11:09

ColinE


DataSet ds = new DataSet();
ds.ReadXml(fileNamePath);
like image 30
ShaneBlake Avatar answered Sep 30 '22 09:09

ShaneBlake