2

There is a question that does almost exactly what I want to do by almost the same name, however I don't know what my XML DOM will look like ahead of time.

I would like to do something like this:

private static IEnumerable<XElement> FindAllContainers(XDocument xml)
{
          IEnumerable<XElement> query = from XElement outer in xml.Root.Elements()
                                        from XElement node in outer.Elements()
                                        where true //Enum.IsDefined(typeof(Role), GetContainerRole(node)) 
                                        select node;
                                        return query;
}

The basic Idea is I want to query against an enumeration of all XElements for any given XML structure. The above code doesn't return any results. With xml containing a large nested XML structure and being an XDocument. The other question manually supplies Elements with the tag names. I don't know what they are ahead of time to set it up statically in the method.

Community
  • 1
  • 1
Joshua Enfield
  • 17,642
  • 10
  • 51
  • 98
  • What kind of results do you want? – John Fisher Apr 20 '12 at 15:59
  • Fundamentally an enumeration of every node in the XDocument (XML). Basically so I can work the set of all nodes as a set rather than as a tree. Although I recently discovered XPath might be more appropriate for my problem I am still curious about the above. – Joshua Enfield Apr 20 '12 at 16:01
  • 1
    Could you use XPath for this? [link][1] [1]: http://stackoverflow.com/questions/3642829/how-to-use-xpath-with-xelement-or-linq – vansimke Apr 20 '12 at 16:02
  • This seems kind of odd. Are you really trying to flatten it in the way that the liked question was? If so, you need to blend values from all the parents of a node into each leaf node. If not, a simple recursive enumeration should do the trick. Which way are you going? – John Fisher Apr 20 '12 at 16:03

1 Answers1

7

So it sounds to me like you just want to enumerate through all elements within the document. Well nothing complicated here, just call the Descendants() method (with no arguments) and it will return all elements within the document.

private static IEnumerable<XElement> FindAllContainers(XDocument doc)
{
    return doc.Descendants();
}
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272