XLinq – Linq to XML

Wiele mówi się o technologii Linq (WikipediaMSDN), która jest częścią Framework’a 3.5. Tym samym nie jest trudno znaleźć przykłady wykorzystania tego cuda. W tym artykule chciałbym zaprezentować zapytania Linq do plików XML. Ich prostota w konstruowaniu oraz niesamowita efektywność w działaniu dają wiele możliwości zwolennikom formatu XML.

Rozpocznę od przykładu deklaracji dokumentu XML. Składnia tworzenia owego obiektu jest bardzo prosta, intuicyjna i przyjazna. Wszystkie wymagane do tej operacji elementy znajdują się w przestrzeni nazw System.Xml.Linq.

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "no"),
    new XComment("Sample of RSS"),
    new XElement("rss",
        new XAttribute("version", "2.0"),
        new XElement("channel",
            new XElement("title", "RSS Channel"),
            new XElement("description", "LINQ to XML"),
            new XElement("link", "http://msdn.microsoft.com/en-us/library/bb387061.aspx"),
            new XElement("item",
                new XElement("title", "First"),
                new XElement("description", "First Article Description"),
                new XElement("pubDate", DateTime.Now.ToString()),
                new XElement("link", "")),
            new XElement("item",
                new XElement("title", "Second"),
                new XElement("description", "Second Article Description"),
                new XElement("pubDate", DateTime.Now.ToString()),
                new XElement("guid", ""))
            )
        )
     );

doc.Save("rss.xml");
XDocument rss = XDocument.Load("rss.xml");
Console.WriteLine(rss.ToString());

W powyższym przykładzie zauważyć można hierarchiczne zagnieżdżanie kolejnych elementów dokumentu. Na koniec zostaje on zapisany, ponownie odczytany oraz wyświetlony w konsoli. Wynik prezentuje się następująco:

Wynik w konsoli dokumentu XML

Kolejny przykład ukazuje jak stworzyć dokument XML w połączeniu z narzędziem LINQ to SQL Classes, którego zadaniem jest wyciągnięcie rekordów z bazy AdventureWorks.

var db = new AdventureWorksDataContext();
XDocument xml = new XDocument(
    new XDeclaration("1.0", "utf-8", "no"),
    new XElement("customers",
        from c in db.Customers.Take(7)
        where c.CustomerID > 2
        orderby c.CustomerID
        select new XElement("customer",
                  new XAttribute("id", c.CustomerID),
                  new XElement("firstName", c.FirstName),
                  new XElement("lastName", c.LastName))
        )
    );

Następnie seria zapytań w formacie Linq oraz Lambda Expressions do kolekcji stworzonej powyżej.

var q = from c in xml.Descendants("customer")
        where (int)c.Attribute("id") <= 5 && (int)c.Attribute("id") > 3
        select (string)c.Element("firstName") + " " + (string)c.Element("lastName");

var q2 = from c in xml.Elements("customers").Elements()
         let custId = 2
         where (int)c.Attribute("id") == custId
         select c;

var q3 = from customers in xml.Descendants("customers")
         from customer in customers.Descendants("customer")
         select customer;

var q4 = xml.Descendants("customer").Where(c => ((string)c.Element("firstName")).StartsWith("Do"));

var q5 = xml.Descendants("customer").Where(c => (int)c.Attribute("id") > 4 || ((string)c.Element("lastName"))
    .Contains("rr")).OrderByDescending(c2 => (string)c2.Element("lastName"));

Prosty INSERT, UPDATE oraz DELETE.

XElement newC = new XElement("customer",
    new XAttribute("id", 10),
    new XElement("firstName", "Marian"),
    new XElement("lastName", "Ociepka")
    );
xml.Root.Add(new XElement("customer",
    new XAttribute("id", 11),
    new XElement("firstName", "Rysia"),
    new XElement("lastName", "Kowalska"))
    );
xml.Root.Add(newC);

var single2 = xml.Descendants("customer").Single(c => (int)c.Attribute("id") == 5);
single2.Element("firstName").Value = "Jan";

var singleNode = xml.Descendants("customer").Where(c => c.Element("firstName").Value.ToLower()
    .StartsWith("j")).Single(c => (int)c.Attribute("id") == 4);
singleNode.Remove();

Na sam koniec JOIN – prawdziwa siła i rewelacja technologii XLinq. Przykład wykorzystuje dwa ówcześnie stworzone pliki XML, których struktury można się domyśleć.

XDocument customersXml = XDocument.Load("customers.xml");
XDocument countriesXml = XDocument.Load("countries.xml");

var q6 = from cust in customersXml.Descendants("customer")
         join country in countriesXml.Descendants("country")
         on (int)cust.Attribute("countryID") equals (int)country.Attribute("id")
         where (string)country.Value == "Poland"
         select new
         {
             name = (string)cust.Element("firstName"),
             country = country.Value
         };

Promuj

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *