Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, the Users elements don't have GUID attributes. Two suggested options:

  • Look at XDocument.Root.Elements("User")
  • Use Descendants("User") to find all User elements.

I'll stick with the former for the moment. That gives us:

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

Now, we can still tidy this up further. Firstly, let's cast to Guid instead of string:

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

However there's not a lot of reason to use a query expression here... all you're applying is a single predicate. Let's just use the Where method directly:

IEnumerable<XElement> users = 
    XMLDoc.Root
          .Elements("User")
          .Where(el => (Guid) el.Attribute("GUID") == userGUID);

How you lay it out is up to you, of course :) With a longer line, you can probably align everything up under a longer first line:

IEnumerable<XElement> users = XMLDoc.Root
                                    . etc

Now, finally - what about if the User element doesn't have a GUID attribute? Currently, this code will throw an exception. That may be exactly what you want - or it may not. If it's not, you can make it ignore such things by casting to Nullable<Guid> aka Guid? instead:

IEnumerable<XElement> users = 
    XMLDoc.Root
          .Elements("User")
          .Where(el => (Guid?) el.Attribute("GUID") == userGUID);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...