C # simple examples of linq to xml,

Source: Internet
Author: User

C # simple examples of linq to xml,

Data. xml

 1 <?xml version="1.0" encoding="utf-8" ?> 2 <Data> 3   <Products> 4     <Product Name="West Side Story" Price="9.99" SupplierID="1" /> 5     <Product Name="Assassins" Price="14.99" SupplierID="2" />   6     <Product Name="Frogs" Price="13.99" SupplierID="1" /> 7     <Product Name="Sweeney Todd" Price="10.99" SupplierID="3" /> 8   </Products> 9 10   <Suppliers>11     <Supplier Name="Solely Sondheim" SupplierID="1" />12     <Supplier Name="CD-by-CD-by-Sondheim" SupplierID="2" />13     <Supplier Name="Barbershop CDs" SupplierID="3" />14   </Suppliers>15 </Data>

Search for products with a price of more than 10 using linq to xml, and print the Supplier name and product name;

 1             XDocument doc = XDocument.Load("data.xml"); 2             var filtered = from p in doc.Descendants("Product") 3                            join s in doc.Descendants("Supplier") 4                            on (int)p.Attribute("SupplierID") 5                            equals (int)s.Attribute("SupplierID") 6                            where (decimal)p.Attribute("Price") > 10 7                            select new 8                            { 9                                ProductName = (string)p.Attribute("Name"),10                                SupplierName = (string)s.Attribute("Name")11                            };12 13             foreach (var v in filtered)14             {15                 Console.WriteLine("SupplierName={0} , ProductName={1}", v.SupplierName, v.ProductName);16             }

Output

SupplierName = CD-by-Sondheim, ProductName = Assassins
SupplierName = Solely Sondheim, ProductName = Frogs
SupplierName = Barbershop CDs, ProductName = Sweeney Todd

 

References

1. in-depth understanding of C # (version 2nd );

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.