Query XML for Descendants named 'customer' in CSharp

Description

The following code shows how to query XML for Descendants named 'customer'.

Example


   //w ww  .  j av  a2s  .co 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("customer")  select c.Name;
            foreach (var item in queryResult)
            {
                Console.WriteLine(item);
            }
        }
    }




















Home »
  C# Tutorial »
    XML »




Load Parse
Document
Element
Attribute
Namespace
Query
Save
Schema
Style