How do I find an XML element by attribute using LINQ to XML?

三世轮回 提交于 2019-12-22 10:38:25

问题


I'm learning LINQ to XML and need to find the existence of an element with a particular attribute. At the moment I'm using:

XElement groupCollectionXml = XElement.Parse(groupCollection.Xml);
IEnumerable<XElement> groupFind =
    from vw in groupCollectionXml.Elements("Group")
    where (string) vw.Attribute("Name") == groupName
    select vw;

if (groupFind.Count() == 0)
    return false;
else
    return true;

I know there is a more concise way of doing this, probably using Any(), but I'm not sure how to rewrite the query to use it. Does anyone have some good advice? Thanks.


回答1:


groupCollectionXml.Elements("Group").Any(
    vw=>(string)vw.Attribute("Name") == groupName
  );



回答2:


Thanks to the other two answers. I combined the conciseness of one with the correctness of another, then stirred and came up with this which works well:

groupCollectionXml.Elements("Group").Any(
  vw => string.Equals(vw.Attribute("Name").Value, groupName, StringComparison.OrdinalIgnoreCase)
);



回答3:


groupCollectionXml.
    Elements("Group").
    Where(item=>String.
        Equals(item.Attribute("Name"), groupName, OrdinalIgnoreCase)).
    Any();

if you want it all on one line



来源:https://stackoverflow.com/questions/606817/how-do-i-find-an-xml-element-by-attribute-using-linq-to-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!