c# - 为什么这个 XElement 查询不能在我的 xml 上运行

标签 c# linq linq-to-xml xelement

我的 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 行上出错了。

最佳答案

你想要这样的东西:

var element = doc.Descendants("node").Where(x => x.Attribute("name") != null && x.Attribute("name").Value == "somekey").FirstOrDefault();

编辑:编辑以从结果中获取第一个元素;

关于c# - 为什么这个 XElement 查询不能在我的 xml 上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2413395/

相关文章:

LINQ 到 SQL -

c# - Linq过滤属性的 setter/getter

c# - 缩进 XML,但保持其他一切不变

c# - Linq to XML 获取一对多元素名称和属性名称/值

c# - Linq to Object/XML 其中元素不存在

c# - 如何从PictureBox获取真实图像像素点x,y

c# - 项目或单独项目中的命名空间

c# - 如何获取 Autofac for WebAPI2 的容器?

wpf - 使用 MVVM ViewModel 将 XDocument 显示为 WPF TreeView

c# - 如何在.Net C# 中绕过 SSL 证书发出 HTTPS SOAP 请求?