views:

534

answers:

3

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

Thanks,

+1  A: 

hey,

I hope I understand your question... anyway - Assuming that you use asp.net since you mentioned Linq, dictionaries are your best choice.

you can find more about them here: http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

In general, dictionary holds key/value pairs so you don't have to use the commas and be able to use loops like you should.

Hope that helps!

yn2
A: 

If data is read only have you considered using Xslt to format it into a Html table?

Here is an article I found on stackoverflow that covers this...

Then it seems like the child elements of could change all they wanted yet they would still be render to your grid (html table)...

J.13.L
+1  A: 

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());
xcud