15.3. Querying the Contents of an XML Document
Problem
You have a large and complex XML document, and you need to find various pieces of information, such as all the information contained within a specific element and having a particular attribute setting. You want to query the XML structure without having to iterate through all the nodes in the XML document and search for a particular item by hand.
Solution
Use the new Language Integrated Query (LINQ) to XML API to query the XML document for the items of interest. LINQ allows you to select elements based on element and attribute values, order the results, and return an IEnumerable
-based collection of the resulting data, as shown in Example 15-2.
Example 15-2. Querying an XML document with LINQ
private static XDocument GetAClue( ) { return new XDocument( new XDeclaration("1.0", "UTF-8", "yes"), new XElement("Clue", new XElement("Participant", new XAttribute("type", "Perpetrator"), "Professor Plum"), new XElement("Participant", new XAttribute("type", "Witness"), "Colonel Mustard"), new XElement("Participant", new XAttribute("type", "Witness"), "Mrs. White"), new XElement("Participant", new XAttribute("type", "Witness"), "Mrs. Peacock"), new XElement("Participant", new XAttribute("type", "Witness"), "Mr. Green"), new XElement("Participant", new XAttribute("type", "Witness"), "Miss Scarlet"), new XElement("Participant", new XAttribute("type", "Victim"), "Mr. Boddy") ) ); }
Notice how similar the structure of the XML and the structure of ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.