Ignacio Ignacio - 2 months ago 6
C# Question

Find Elements by Attribute using XDocument

This query seems to be valid, but I have 0 results.

IEnumerable<XElement> users =
(from el in XMLDoc.Elements("Users")
where (string)el.Attribute("GUID") == userGUID.ToString()
select el);


My XML is as follows:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Users>
<User GUID="68327fe2-d6f0-403b-a7b6-51860fbf0b2f">
<Key ID="F7000012ECEAD101">
...
</Key>
</User>

</Users>


Do you have any clues to shed some light onto this?

Answer

change Users in the 2nd line to User. Like this:

    IEnumerable<XElement> users = (from el in XMLDoc.Root.Elements("User")
                                   where (string)el.Attribute("GUID") ==  userGUID.ToString()
                                   select el);

I'm assuming XMLDoc is an XDocument, and not the root element itself.