zotty
zotty

Reputation: 817

How do I differentiate between different descendents with the same name?

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>?

Upvotes: 1

Views: 214

Answers (2)

Anthony Pegram
Anthony Pegram

Reputation: 126992

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.

Upvotes: 3

Andrew Bezzub
Andrew Bezzub

Reputation: 16032

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.

Upvotes: 1

Related Questions