Query XML for Attributes named 'Company' in CSharp

Description

The following code shows how to query XML for Attributes named 'Company'.

Example


   //  w  ww . j  a v  a 2 s  .  c  om

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("Book").Attributes("Company")
                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