Using Linq To query Xml : Query « XML LINQ « C# / CSharp Tutorial






using System.Text;
using System.Xml.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
    class LinqToXml
    {
        static void Main()
        {
            XDocument doc = XDocument.Load("data.xml");
            var filtered = from p in doc.Descendants("Product")
                           join s in doc.Descendants("Supplier")
                           on (int)p.Attribute("SupplierID")
                               equals (int)s.Attribute("SupplierID")
                           where (decimal)p.Attribute("Price") > 10
                           orderby (string)s.Attribute("Name"),
                                   (string)p.Attribute("Name")
                           select new
                           {
                               SupplierName = (string)s.Attribute("Name"),
                               ProductName = (string)p.Attribute("Name")
                           };
            foreach (var v in filtered)
            {
                Console.WriteLine("Supplier={0}; Product={1}",
                                  v.SupplierName, v.ProductName);
            }
        }
    }

//File: data.xml
/*
<?xml version="1.0"?>
<Data>
  <Products>
    <Product Name="E" Price="9.99" SupplierID="1" />
    <Product Name="A" Price="14.99" SupplierID="2" />
    <Product Name="C" Price="13.99" SupplierID="1" />
    <Product Name="D" Price="10.99" SupplierID="3" />
  </Products>
</Data>
*/








31.4.Query
31.4.1.Query XML by select an element
31.4.2.Query XML: All descendants in document
31.4.3.Query XML: All distinct descendants in document
31.4.4.Query XML: Attributes named 'Company'
31.4.5.Query XML: Attributes of descendants named 'customer'
31.4.6.Query XML: Descendants named 'customer'
31.4.7.Query XML: Earliest year in which orders were placed
31.4.8.Query XML: Values of customer attributes named 'Company'
31.4.9.Query XML: Values of descendant attributes named 'orderYear'
31.4.10.Query XML: attributes named 'orderYear'
31.4.11.Using Linq To query Xml