使用子属性查询子元素的 XElement
以下是 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();
}
但我什么也没得到。我希望能够为每个“事物”选择“子”,其中属性“lang”等于一个值。
我也尝试过这个,但没有成功。
var FrenchSet = single.Elements("Child")
.Where(y => y.Attribute("lang").Equals("f"))
.Select(x => x.Value).FirstOrDefault();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在检查
XAttribute
对象是否等于字符串"e"
。由于
XAttribute
对象永远不等于字符串,因此它不起作用。您需要检查
XAttribute
对象的Value
,如下所示: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'sValue
, like this:您正在将属性对象与字符串“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:
正如 Slaks 所说,您正在检查属性而不是其值是“e”。您也不需要
select e.Value
因为“Child”节点没有值,它们有“record”子节点。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.