Blog Stats
  • Posts - 298
  • Articles - 0
  • Comments - 1353
  • Trackbacks - 0

 

Tuesday, November 13, 2007

LINQ to XML - Something to be excited about

The more I look into the LINQ features of the Framework, the more excited I get.  In particular, LINQ to XML has an incredible amount of productivity when working with XML documents. 

"But Eric, " I hear you say, "we can work with XML with existing framework items."

Yes and No.

The problem myself and others are faced with when working with XML is the sheer amount of choices.  You have to learn when to use the XML DOM, XPATH, XSLT, and the various other means of manipulating XML.  They all have their tradeoffs and benefits but they are all very different to work with.  Not that this is insurmountable, if you work with XML often, it's not going to be a problem for you.  But if you are like me, and spend most of your time on internal apps with a database, you don't really use XML all that much, so when the need actually arises you find yourself swimming in documentation and trying to figure out the best way to do what needs to be done.  By providing LINQ to XML anyone who understands LINQ should be able to quickly jump in and manipulate XML, which I think is absolutely huge.

Interestingly enough, I like the VB version of LINQ better than the C#.  I'd like to put a short code sample here to show why.  The VB and C# for creating an employee XML node is roughly the same.  By using the XElement LINQ object, I can chain down the xml node and fill in all the values I want, like so:

       Dim employee As New XElement("employee", _
            New XElement("name", "Eric Wise"), _
            New XElement("department", "Information Technology"), _
            New XElement("title", "Application Development Manager"), _
        )

Very easy both to write and read compared to some other solutions.  However, there's an even neater way in VB .NET.  You can actually use literal xml.  Check this out:

       Dim xml As XElement = <employee>
                                  <name>Eric Wise</name>
                                  <department>Information Technology</department>
                                  <title>Application Development Manager</title>
                              </employee>

Is that not, the coolest, most readable XML generation you've ever seen?!  Programatically you can replace my string literals with variables using your traditional ASP Script tags <%= %>.  This is an incredibly powerful method of generating maintainable XML code.

I hope this gets everyone excited about LINQ to XML!

posted @ Tuesday, November 13, 2007 5:53 AM | Feedback (7)

 

 

Copyright © Eric Wise