我的 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/