Reputation: 408
I have the following XML and want to return all "schools" children but I only get the first one. (jeffersion/08.36) I looked high and low and banged my head. What am I missing?
<users>
<user>
<role>janitor</role>
<schools>
<school_name>jefferson</school_name>
<keycode>80.36</keycode>
<school_name>mainline</school_name>
<keycode>64.36</keycode>
<school_name>south side</school_name>
<keycode>31</keycode>
</schools>
</user>
</users>
This is only returning the first record.
var results= from schools in myXmlDoc.Descendants("schools")
select new
{
SchoolName = schools.Element("school_name").Value,
KeyCode = schools.Element("keycode").Value
};
I've also tried:
var results= (from schools in myXmlDoc.Descendants("schools")
select new
{
SchoolName = schools.Element("school_name").Value,
KeyCode = schools.Element("keycode").Value
}.ToList();
This gets the values BUT only for the first school:
var schools = (from c in xml.Descendants("user")
select new
{
Name = c.Element("role").Value,
Fields = c.Elements("schools")
.Select(f => new
{
SchoolName = f.Element("school_name").Value,
Keycode = f.Element("keycode").Value
}).ToArray()
}).ToList();
Upvotes: 0
Views: 3910
Reputation: 6493
You only have one <schools>
element in your source, which is why only one entry is being returned. The XML isn't particularly nicely structured - it would be good to have a <school>
element containing each school_name/keycode pair. But assuming you have to live with it, the following should work:
var results= from school in myXmlDoc.Descendants("school_name")
select new
{
SchoolName = school.Value,
KeyCode = school.ElementsAfterSelf("keycode").First().Value
};
Upvotes: 1
Reputation: 834
This may be helpful:
var result = from c in XElement.Load("Student.xml").Elements("schools") select c ;
// Execute the query foreach (var students in result ) { //do something }
Upvotes: 1