Csharp/C Sharp/XML LINQ/Query — различия между версиями

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

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

A Simple XML Query Using LINQ to XML

 
using System;
using System.Linq;
using System.Xml.Linq;
public class MainClass {
    public static void Main() {
        XElement books = XElement.Parse(
          @"<books>
        <book>
          <title>P</title>
          <author>J</author>
        </book>
        <book>
          <title>W</title>
          <author>B</author>
        </book>
        <book>
          <title>C</title>
          <author>A</author>
        </book>
    </books>");
        var titles =
         from book in books.Elements("book")
         where (string)book.Element("author") == "J"
         select book.Element("title");
        foreach (var title in titles)
            Console.WriteLine(title.Value);
    }
}


Get Node by type with OfType

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Reflection;
using System.Xml.Linq;
class Program {
    static void Main(string[] args) {
        XElement xml = XElement.Load("Employee.xml");
        IEnumerable<XComment> record = xml.Nodes().OfType<XComment>();
        foreach (XComment comment in record)
            Console.WriteLine(comment);
    }
}


Query string array by its element length

 
using System;
using System.Linq;
class HelloWorld {
    static void Main() {
        string[] words = { "hello", "wonderful", "linq", "beautiful", "world" };
        var shortWords = from word in words
                         where word.Length <= 5
                         select word;
        foreach (var word in shortWords)
            Console.WriteLine(word);
    }
}


Query XML document by attribute

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Reflection;
using System.Xml.Linq;
class Program {
    static void Main(string[] args) {
        XElement xml = XElement.Load("Employee.xml");
        var query = from s in xml.Elements("salary").Elements("idperson")
                    where (int)s.Attribute("year") == 2004
                    select s;
        foreach (var record in query) {
            Console.WriteLine("Amount: {0}", (string)record.Attribute("salaryyear"));
        }
    }
}


Query XML document with Ancestors and First

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Reflection;
using System.Xml.Linq;
class Program {
    static void Main(string[] args) {
        XElement xml = XElement.Load("Employee.xml");
        var record = xml.Descendants("firstname").First();
        foreach (var tag in record.Ancestors())
            Console.WriteLine(tag.Name);
    }
}


Query XML document with where clause

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Reflection;
using System.Xml.Linq;
class Program {
    static void Main(string[] args) {
        XElement xml = XElement.Load(@"Employee.xml");
        var query = from p in xml.Elements("person")
                    where (int)p.Element("id") == 1
                    select p;
        foreach (var record in query) {
            Console.WriteLine("Employee: {0} {1}",
                                                record.Element("firstname"),
                                                record.Element("lastname"));
        }
    }
}


Query XML with Descendants

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Reflection;
using System.Xml.Linq;
class Program {
    static void Main(string[] args) {
        XElement xml = XElement.Load("Employee.xml");
        var query = from p in xml.Descendants("person")
                    join s in xml.Descendants("id")
                    on (int)p.Element("id") equals (int)s.Attribute("id")
                    select new {
                        FirstName = p.Element("firstname").Value,
                        LastName = p.Element("lastname").Value,
                        Amount = s.Attribute("salaryyear").Value
                    };
        foreach (var record in query) {
            Console.WriteLine("Employee: {0} {1}, Salary {2}", record.FirstName,
                                                            record.LastName,
                                                            record.Amount);
        }
    }
}


Query XML with namespace

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Reflection;
using System.Xml.Linq;
class Program {
    static void Main(string[] args) {
        XElement xml = XElement.Load("Hello.xml");
        XNamespace o = "urn:schemas-microsoft-com:office:office";
        var query = from w in xml.Descendants(o + "Author")
                    select w;
        foreach (var record in query)
            Console.WriteLine("Author: {0}", (string)record);
    }
}


Use Linq query to get XML document elements

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Reflection;
using System.Xml.Linq;
class Program {
    static void Main(string[] args) {
        XElement xml = XElement.Load("Employee.xml");
        XElement html = new XElement("HTML",
                                new XElement("BODY",
                                    new XElement("TABLE",
                                        new XElement("TH", "ID"),
                                        new XElement("TH", "Full Name"),
                                        new XElement("TH", "Role"),
                                            from p in xml.Descendants("person")
                                            join r in xml.Descendants("role") on (int)p.Element("idrole") equals (int)r.Element("id")
                                            select new XElement("TR",
                                                            new XElement("TD", p.Element("id").Value),
                                                            new XElement("TD", p.Element("firstname").Value + " " + p.Element("lastname").Value),
                                                            new XElement("TD", r.Element("roledescription").Value)))));
        html.Save(@"C:\People.html");
    }
}


use Linq to query an XML document

 
using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

static class HelloLinqToXml {
    static void Main() {
        var books = new[] {
      new {Title="A", Publisher="M", Year=2005 },
      new {Title="W", Publisher="M", Year=2006 },
      new {Title="R", Publisher="M", Year=2006 }
    };
        XElement xml = new XElement("books",
          from book in books
          where book.Year == 2006
          select new XElement("book",
            new XAttribute("title", book.Title),
            new XElement("publisher", book.Publisher)
          )
        );
        Console.WriteLine(xml);
    }
}