LA.NET [EN]

May 17

Now that we know the basics, it”s time to see how we can use this new API with LINQ. In this post, we”ll start by seeing how we can filter an XML document and then we”ll how easy it is to transform an existing XML tree into a different one.

Lets start by defining an existing XML tree (we”ll simply reuse the tree from the previous example):

 

var xml = new XElement( “clients”,
                    new XElement(“client”,
                        new XAttribute(“id”,1),
                        new XElement( “name”, “Luis”),
                        new XElement( “country”, “Portugal”)
                    ),
                    new XElement(“client”,
                        new XAttribute(“id”,2),
                        new XElement( “name”, “John”),
                        new XElement( “country”, “England”)
                    ),new XElement(“client”,
                        new XAttribute(“id”,3),
                        new XElement( “name”, “Paulo”),
                        new XElement( “country”, “Portugal”)
                    )
                );

 

This will produce XML similar to the next snippet:

<clients>
  <client id=”1″>
    <name>Luis</name>
    <country>Portugal</country>
  </client>
  <client id=”2″>
    <name>John</name>
    <country>England</country>
  </client>
  <client id=”3″>
    <name>Paulo</name>
    <country>Portugal</country>
  </client>
</clients>

Ok, now we”re ready to start playing with LINQ. Lets start by getting only the portuguese clients:

var transformed = from client in xml.Elements()
                where client.Element(“country”).Value.CompareTo(“Portugal”) == 0
                select client;

The previous code returns an IEnumerable<XElement> collection. If you”re using a console app and you want to confirm that everything is working, you can simply wrap that collection on an XElement and pass it to the console.WriteLine method:

Console.WriteLine(new XElement(“portugueseClients”, transformed));

That should print the following XML:

<orders>
  <order id=”1″ clientId=”1″>
    <item id=”1″ quantity=”10″ />
    <item id=”2″ quantity=”5″ />
  </order>
  <order id=”2″ clientId=”1″>
    <item id=”1″ quantity=”10″ />
  </order>
</orders>

Even though I”m just filtering the results, you could also all the other cool LINQ operatores over an existing XML tree!

One of the most common things you need to do when you work with XML is to transform an existing tree into another one (for instance, you”ll need doing this when you”re trying to integrate two applications which understand different XML messages). In this case, lets suppose that you need to transform the previous XML tree in another where all the info is represented through attributes. Here”s how that would look like:

<compatClients>
  <compatClientElement id=”1″ name=”Luis” country=”Portugal” />
  <compatClientElement id=”2″ name=”John” country=”England” />
  <compatClientElement id=”3″ name=”Paulo” country=”Portugal” />
</compatClients>

Here”s one LINQ query that will give you the previous results:

var transformed = new XElement(“compatClients”,
    ( from client in xml.Elements()
           select new XElement(“compatClientElement”,
                 new XAttribute(“id”, client.Attribute(“id”).Value),
                  new XAttribute(“name”, client.Element(“name”).Value),
                  new XAttribute(“country”, client.Element(“country”).Value)) )
       );

Well, not really that hard, right? btw, lets also assume that you”ve got several XML elements (instead of just two) and that all of them should be transformed in attributes. Does that mean that you need to create all those attributes manually? Hell, no! You can simply use another LINQ query to achieve that. here”s a variation of the previous snippet that produces similar results:

var transformed = new XElement(“compatClients”,
                           ( from client in xml.Elements()
                           select new XElement(“compatClientElement”,
                               new XAttribute(“id”, client.Attribute(“id”).Value),
                               (from elem in client.Elements()
                                    select new XAttribute(elem.Name, elem.Value)
                                ) ) ) );

You”ve got love LINQ To XML!

Another common scenario is transforming an object graph into an XML message. For instance, suppose you hav
e the several orders represented by the following object graph (I”m just using anonymous types to represent them. You”ll probably have a predefined type on a real scenario):

var orders = new[] {
                new{ Id = 1,
                    ClientID = 1,
                    OrderItems =  new[]{ new {ItemId = 1, Quantity = 10}, new {ItemId = 2, Quantity = 5} }
                    },
                new{ Id = 2,
                    ClientID = 1,
                    OrderItems =  new[]{ new {ItemId = 1, Quantity = 10} }
                    }
            };

 

Now, we need to build a new XML message that looks like this:

<orders>
  <order id=”1″ clientId=”1″>
    <item id=”1″ quantity=”10″ />
    <item id=”2″ quantity=”5″ />
  </order>
  <order id=”2″ clientId=”1″>
    <item id=”1″ quantity=”10″ />
  </order>
</orders>

Which, as you must be expecting, is easily doable with the next snippet:

var transformed = new XElement(“orders”,
                               from order in orders
                               select new XElement(“order”,
                                   new XAttribute(“id”, order.Id),
                                   new XAttribute(“clientId”, order.ClientID),
                                   from item in order.OrderItems
                                   select new XElement(“item”,
                                           new XAttribute(“id”, item.ItemId),
                                           new XAttribute(“quantity”, item.Quantity))
                                           )
                                           );

I”ve just showed one or two things that are easily achieved with this API. I hope that by now I”ve already convinced on how flexible and powerful this new API is. I was actually able to build all the demo code presented in this post in about 2 minutes (including the queries). If I was using the old DOM API, I”d took at least thrice as long to get the some results (and I”m assuming that I know the API well enough).

As I”ve said in one of the previous posts, I”m really enjoying working with this new API. Since I”ve started using it, I”ve noticed an improvement in my productivity, which is good, because it means that now I have more free time to see what”s happening on the Euro 2008 :)

1 comment so far

  1. gzsprrxudh
    4:38 am - 1-13-2010

    UOAIFD jjnrkcsbrbib, [url=http://imvzthbsojnr.com/]imvzthbsojnr[/url], [link=http://cjhhplnnyacs.com/]cjhhplnnyacs[/link], http://hcunznnimngc.com/