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.
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 ...
}
                        DataSet ds = new DataSet();
ds.ReadXml(fileNamePath);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With