Query XML for All distinct descendants in document in CSharp

Description

The following code shows how to query XML for All distinct descendants in document.

Example


   /* w  w  w . j  ava 2 s  .c  o m*/

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

    class Program
    {
        static void Main(string[] args)
        {
            XDocument customers =  
            new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
                          new XDocumentType("Books", null, "Books.dtd", null),
                          new XProcessingInstruction("Book", "out-of-print"),
                          new XElement("Books",new XElement("Book",new XAttribute("type", "Author"),
                             new XElement("FirstName", "J"),
                             new XElement("LastName", "R")),
                           new XElement("Book",
                             new XAttribute("type", "Author"),
                             new XElement("FirstName", "E"),
                             new XElement("LastName", "B"))));

            var queryResult = from c in customers.Descendants() select c.Name;
            foreach (var item in queryResult.Distinct())
            {
                Console.WriteLine(item);
            }
        }
    }




















Home »
  C# Tutorial »
    XML »




Load Parse
Document
Element
Attribute
Namespace
Query
Save
Schema
Style