Search code examples
.netxmlcollectionsdata-collection

How to create object collection from an xml


I have an xml like the following

<DataCollection>
  <Data>
    <Name>John</Name>
    <Age>30</Age>
  </Data>
  ... more person
</DataCollection>

I want to create an object (or some type) collection with Name, Age as fields. One problem that I have is I don't know the structure before hand (all I know is, there will be DataCollection and Data) to create a class and then using linq to use select new. Current implementation, I am walking the XML for each Data, read the elements and create a comma separated list.

Is there a better way to do this? The purpose of the XML is to display all the data that is coming in under Data in a data grid.


Solution

  • FWIW here's the LINQ query that'll turn that XML document into a collection of objects:

        var coll = from XElement c in doc.Descendants("Data") 
           select new { 
               Name = c.Element("Name").Value, 
               Age = int.Parse(c.Element("Age").Value) 
           };
    

    But I think what you're really looking for is a way to bind the XML document to a DataGrid directly. One way to do that is to bind your DataGrid to a DataTable and use its WriteXml/ReadXml methods to read/write the file.

    On preview ... I missed the requirement that the structure of the incoming XML is unknown. You can build up a collection of collections of objects without knowing the structure of the Data blocks using this LINQ:

    var coll = from XElement c in loaded.Descendants("Data")
           select (from XElement d in c.Elements() select d.Value);
    

    Or you can generate the CSV with this:

    string csv = string.Join(Environment.NewLine, 
    ( from XElement c in loaded.Descendants("Data") 
      select string.Join(",", 
        (from XElement d in c.Elements() select d.Value).ToArray())
    ).ToArray());