Skip to main content

This program includes a simple LINQ to XML sample query. It shows the minimal code necessary to write a LINQ to XML query.

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Linq;
using System.Xml.Linq;

// --------------------------------------------------------
// Data/bib.xml
// --------------------------------------------------------
// <bib>
//   <book year="1994">
//     <title>TCP/IP Illustrated</title>
//     <author>
//       <last>Stevens</last>
//       <first>W.</first>
//     </author>
//     <publisher>Addison-Wesley</publisher>
//     <price>65.95</price>
//   </book>
//   <book year="1992">
//     <title>Advanced Programming in the Unix environment</title>
//     <author>
//       <last>Stevens</last>
//       <first>W.</first>
//     </author>
//     <publisher>Addison-Wesley</publisher>
//     <price>65.95</price>
//   </book>
//   <book year="2000">
//     <title>Data on the Web</title>
//     <author>
//       <last>Abiteboul</last>
//       <first>Serge</first>
//     </author>
//     <author>
//       <last>Buneman</last>
//       <first>Peter</first>
//     </author>
//     <author>
//       <last>Suciu</last>
//       <first>Dan</first>
//     </author>
//     <publisher>Morgan Kaufmann Publishers</publisher>
//     <price>39.95</price>
//   </book>
//   <book year="1999">
//     <title>The Economics of Technology and Content for Digital TV</title>
//     <editor>
//       <last>Gerbarg</last>
//       <first>Darcy</first>
//       <affiliation>CITI</affiliation>
//     </editor>
//     <publisher>Kluwer Academic Publishers</publisher>
//     <price>129.95</price>
//   </book>
// </bib>

namespace LinqToXmlSample
{
    class Program
    {
        static void Main(string [] args)
        {
            // List all books by Serge and Peter with co-authored books repeated
            XDocument doc = XDocument.Load(SetDataPath() + "bib.xml");

            var b1 = doc.Descendants("book")
                .Where(b => b.Elements("author").Elements("first")
                    .Any(f => (string)f == "Serge"));

            var b2 = doc.Descendants("book")
                .Where(b => b.Elements("author").Elements("first")
                    .Any(f => (string)f == "Peter"));

            var books = b1.Concat(b2);
            foreach (var q in books)
            {
                Console.WriteLine(q);
            }

            Console.ReadLine();
        }

        static public string SetDataPath()
        {
            string path = Environment.CommandLine;

            while (path.StartsWith("\""))
            {
                path = path.Substring(1, path.Length - 2);
            }

            while (path.EndsWith("\"") || path.EndsWith(" "))
            {
                path = path.Substring(0, path.Length - 2);
            }

            path = Path.GetDirectoryName(path);

            return Path.Combine(path, "data\\");
        }
    }
}