[英]Quering XElements for children with children attributes
这是XML大纲:
<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>
我有以下内容:
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();
}
但我什么都没回来。 我希望能够为每个“Thing”选择“Child”,其中属性“lang”等于一个值。
我也尝试了这个,但没有奏效。
var FrenchSet = single.Elements("Child")
.Where(y => y.Attribute("lang").Equals("f"))
.Select(x => x.Value).FirstOrDefault();
您正在检查XAttribute
对象是否等于字符串"e"
。
由于XAttribute
对象永远不等于字符串,因此它不起作用。
您需要检查XAttribute
对象的Value
,如下所示:
where y => y.Attribute("lang").Value == "e"
您正在将属性对象与字符串“e”进行比较,而不是attrbute对象的值。 您还返回节点的值而不是节点的值。 由于该值为空,因此您只需获取空字符串。
试试这个:
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();
正如Slaks所说,你正在检查属性不是它的值是“e”。 您也不需要select e.Value
因为“Child”节点没有具有“记录”子节点的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.