为什么这个 XElement 查询不能在我的 xml 上运行
我的 xml 看起来像:
<nodes>
<node name="somekey">
<item name="subject">blah</item>
<item name="body">body</item>
</node>
</nodes>
到目前为止我的代码是:
XDocument doc = XDocument.Load(HttpContext.Current.Server.MapPath(String.Format("~/files/{0}/text.xml", "en")));
if (doc != null)
{
XElement element = doc.Elements().Where(e => e.Elements().Any() && e.Attribute("name").Value == "someKey").First();
}
我收到一条错误消息:
Sequence contains no elements
我的查询错误吗?
我单步执行了代码,但它在 XElement 线上出错了。
My xml looks like:
<nodes>
<node name="somekey">
<item name="subject">blah</item>
<item name="body">body</item>
</node>
</nodes>
And my code so far is:
XDocument doc = XDocument.Load(HttpContext.Current.Server.MapPath(String.Format("~/files/{0}/text.xml", "en")));
if (doc != null)
{
XElement element = doc.Elements().Where(e => e.Elements().Any() && e.Attribute("name").Value == "someKey").First();
}
I am getting an error saying:
Sequence contains no elements
Is my query wrong?
I stepped through the code, and it errors out on the line with XElement..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想要这样的东西:
编辑:编辑以从结果中获取第一个元素;
You want something like this:
Edit: Edited to grab first element from result;
您还可以使用:
说明:
doc.Elements()
获取根元素,即nodes
。然后.Elements()
选择该元素的子元素,其中只有一个node
。然后在该节点集上执行.Where()
,这就是您想要的。 lambda 选择具有子元素且具有值为“somekey”的属性“name”的元素。您的原始代码没有获取子元素的子元素。因此原始结果集是空的。
您也可以使用 .Descendants() 来完成此操作,但对我来说,这感觉有点草率和松散。
You could also use:
Explanation:
The
doc.Elements()
grabs the root element, which isnodes
. Then the.Elements()
selects the child elements of that, which is just one,node
. The.Where()
is then performed on that nodeset, which is what you want. The lambda selects those elements that have child elements, and also have an attribute "name" with value "somekey".Your original code was not getting the Child-of-Child-elements. Hence the original result set was empty.
You could also do this with
.Descendants()
but that feels a little sloppy and loose, to me.