Quering XElements for children with children attributes
Here is the XML outline:
<Root>
<Thing att="11">
<Child lang="e">
<record></record>
<record></record>
<record></record>
</Child >
<Child lang="f">
<record></record>
<record></record>
<record></record>
</Child >
</Thing>
</Root>
I have the following:
TextReader reader = new StreamReader(Assembly.GetExecutingAssembly()
.GetManifestResourceStream(FileName));
var data = XElement.Load(reader);
foreach (XElement single in Data.Elements())
{
// english records
var EnglishSet = (from e in single.Elements("Child")
where e.Attribute("lang").Equals("e")
select e.Value).FirstOrDefault();
}
But I'm getting back nothing. I want to be able to for Each "Thing" select the "Child" where the attribute "lang" equals a value.
I have also tried this, which has not worked.
var FrenchSet = single.Elements("Child")
.Where(y => y.Attribute("lang").Equals("f"))
.Select开发者_如何转开发(x => x.Value).FirstOrDefault();
You're checking whether the XAttribute
object is equal to the string "e"
.
Since an XAttribute
object is never equal to a string, it doesn't work.
You need to check the XAttribute
object's Value
, like this:
where y => y.Attribute("lang").Value == "e"
You are comparing the attribute object with the string "e", rather than the value of the attrbute object. You're also returning the value of the node rather than the node. Since the value is empty, you'll just get the empty string.
Try this instead:
var EnglishSet = (from e in single.Elements("Child")
where e.Attribute("lang").Value == "e"
select e).FirstOrDefault();
var EnglishSet = (from e in single.Elements("Child")
where e.Attribute("lang").Value.Equals("e")
select e).FirstOrDefault();
As Slaks stated you were checking that the attribute not it's value was "e". You also don't need select e.Value
because the "Child" nodes don't have a value they have "record" children.
精彩评论