2

I'm new to C# so this could be a simple answer. I have a List of XElements coming in from an API. I need to convert it to a datatable. How can I do that?

List of XElements:

<person><personid>1</personid><name>person1</name></person>
<person><personid>2</personid><name>person2</name></person>

I need it in the following data table format

    PersonID | Name
    --------------
    1         person1
    2         person2

Another thing is I dont know the nodes at design time. So the XElement could be of the format

<anyrootnode><anynumberofchildnodes/></anyrootnode>
AverageJoe
  • 436
  • 4
  • 13
  • 2
    What have you tried? Have you written any code? – NetMage Mar 28 '18 at 21:23
  • 1
    Possible duplicate of [load xelement into a datatable](https://stackoverflow.com/questions/7602581/load-xelement-into-a-datatable) – Tim Mar 28 '18 at 21:36
  • If you know the schema in advance, see [How to get a tablerow out of an xelement?](https://stackoverflow.com/q/32139449/3744182). – dbc Mar 28 '18 at 21:57

1 Answers1

4

DataTable has a function named ReadXml which is used to read Xml.

string xml = XElements.ToString();
DataTable dt = new DataTable();
dt.ReadXml(new System.IO.StringReader(xml));
Sailesh Babu Doppalapudi
  • 1,534
  • 1
  • 10
  • 22