如何使用Linq到Xml获取单个XElement对象?

时间:2022-09-30 20:51:02

I would like to use Linq to Xml to get a single XElement from a .xml file by attribute name, similar to how you retrieve single objects in Linq to Sql by Id below:

我想使用Linq to Xml通过属性名从.xml文件中获取单个XElement,类似于在下面通过Id检索Linq到Sql中的单个对象:

var singleDog = context.Dogs.Single(p => p.Id == int.Parse(Id));

Is this possible?

这可能吗?

1 个解决方案

#1


7  

Absolutely. Just use something like:

绝对。只需使用以下内容:

xdoc.Descendants()
    .Where(x => x.HasAttribute("id") && x.Attribute("id")==id)
    .Single();

There may be a more efficient way of doing it, admittedly...

可以肯定的是,有一种更有效的方法可以做到这一点......

#1


7  

Absolutely. Just use something like:

绝对。只需使用以下内容:

xdoc.Descendants()
    .Where(x => x.HasAttribute("id") && x.Attribute("id")==id)
    .Single();

There may be a more efficient way of doing it, admittedly...

可以肯定的是,有一种更有效的方法可以做到这一点......