views:

53

answers:

2

I've got some XML I'm trying to import with c#, which looks something like this:

<root>
<run>
    <name = "bob"/>
    <date = "1958"/>
</run>
<run> 
    <name = "alice"/>
    <date = "1969"/>
</run>
</root>

I load my xml using

XElement xDoc=XElement.Load(filename);

What I want to do is have a class for "run", under which I can store names and dates:

 public class RunDetails
{
    public RunDetails(XElement xDoc, XNamespace xmlns)
    {
        var query = from c in xDoc.Descendants(xmlns + "run").Descendants(xmlns + "name") select c;
        int i=0;
        foreach (XElement a in query)
        {
            this.name= new NameStr(a, xmlns); // a class for names
            Name.Add(this.name); //Name is a List<NameStr>
            i++;
        }
        // Here, i=2, but what I want is a new instance of the RunDetails class for each <run>
     }
  }

How can I set up my code to create a new instance of the RunDetails class for every < run>, and to only select the < name> and < date> inside a given < run>?

+1  A: 

You need to have some parent element in your xml cause your one is not valid. If you have following xml

<root>
    <run>
        <name = "bob"/>
        <date = "1958"/>
    </run>
    <run> 
        <name = "alice"/>
        <date = "1969"/>
    </run>
</root>

you can load it to XDocument and iterate through children of the root element. For each run child element you can create RunDetails.

Andrew Bezzub
Apologies, yes there is a root element there - I omitted it thinking it would make the post clearer. How do you iterate through an XDocument? I've been using XElement, which I thought was more user friendly.
zotty
You can use both XDocument and XElement. Usually XDocument is used as root for xml document.
Andrew Bezzub
+3  A: 

You can just LINQ to XML to create an IEnumerable from your XML.

IEnumerable<RunDetail> runDetails = from run in xdocument.Descendants("run")
                                select new RunDetail
                                {
                                    Name = run.Element("name").Value,
                                    Date = int.Parse(run.Element("date").Value)
                                };

This, of course, suggests there's a class named RunDetail with public Name and Date (int for the year) properties. You can iterate over the enumerable as it is, or if you need more explicit access to the individual members, you can use .ToList() or .ToArray() to convert the query.

Anthony Pegram
IEnumerable - that's exactly what I needed - cheers :)
zotty