Programming XML with XLINQ

To illustrate the power of XLINQ, let’s see some code.

Simple XML Document:

<contacts>
  <contact>
    <name>Sandra Day O’Connor</name>
    <phone>(503) 555-7123</phone>
  </contact>
   …
</contacts>

Programming XML today

  XmlDocument doc = new XmlDocument()#160; 
                               // 1. Imperative model
  XmlElement contacts = doc.CreateElement("contacts");
                               // 2. Document centric

  foreach (Customer c in customers)
                               // 3. No integrated queries
    if (c.Country == "USA")
    {
      XmlElement e = doc.CreateElement("contact");

      XmlElement name  = doc.CreateElement("name");
      name.InnerText   = c.CompanyName;
      e.AppendChild(name);     // 4. Memory intensive

      XmlElement phone = doc.CreateElement("phone");
      phone.InnerText  = c.Phone;
      e.AppendChild(phone);

      contacts.AppendChild(e);
    }

  doc.AppendChild(contacts);

Programming XML with XLINQ.

  XElement contacts = new XElement("contacts",
                                        // 1. Declarative model
    from c in customers                 // 2. Element centric
    where c.Country == "USA"
    select new XElement("contact",
      new XElement("name", c.CompanyName), 
                                        // 3. Integrated queries
      new XElement("phone", c.Phone)    // 4. Smaller and faster
    )
  );

 

Advertisements

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: