Csharp/CSharp Tutorial/XML LINQ/XElement — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 15:16, 26 мая 2010

Get Descendants for a node

<source lang="csharp">using System; using System.Linq; using System.Xml.Linq;

   class LinqToXml
   {
       static void Main(string[] args)
       {
           XElement doc = XElement.Load("table.xml");
           var products = from prodname in doc.Descendants("products") select prodname.Value;
           foreach (var prodname in products)
           Console.WriteLine("Product"s Detail = {0}\t", prodname);
       }
   }</source>

Parse Load xml from hard coded string

<source lang="csharp">using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Text;

   class Program
   {
       static void Main(string[] args)
       {
           XElement xdoc = XElement.Parse(@"
                   <customers>
                     <customer ID=""A"">
                       <order Item=""Widget"" Price=""100"" />
                       <order Item=""Tire"" Price=""200"" />
                     </customer>
                   </customers>
                   ");
           Console.WriteLine(xdoc);
       }
   }</source>

XML Fragments

<source lang="csharp">using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Text;

   class Program
   {
       static void Main(string[] args)
       {
           XElement xcust = 
               new XElement("customers",
                   new XElement("customer",
                       new XAttribute("ID", "A"),
                       new XAttribute("City", "New York"),
                       new XAttribute("Region", "North America"),
                       new XElement("order",
                           new XAttribute("Item", "Widget"),
                           new XAttribute("Price", 100)
                     ),
                     new XElement("order",
                       new XAttribute("Item", "Tire"),
                       new XAttribute("Price", 200)
                     )
                   )
               );
           string xmlFileName = "e.xml";
           xcust.Save(xmlFileName);
           XElement xcust2 = XElement.Load(xmlFileName);
           Console.WriteLine(xcust);
       }
   }</source>