XLinq StreamingElement

6/14/2006 2:14:38 AM

XLinq StreamingElement

The functional style of XLinq is a huge improvement in ease of use over the existing DOM and SAX-based approaches to reading and writing XML in .NET. This document XLinq XML Programming Refactored by Erik Meijer illustrates the tremendous benefits in simplicity one gains when using XLinq over DOM with numerous examples. (I don’t really need to demonstrate advantages over SAX.) Below is one of his examples:

Here is DOM:

  Dim PO As New XmlDocument

  Dim purchaseOrder As XmlElement = _
			   PO.CreateElement("purchaseOrder")
  PO.AppendChild(purchaseOrder)

  Dim orderDate XmlAttribute = PO.CreateAttribute("orderDate")
  orderDate.Value = "1999-10-20"
  purchaseOrder.Attributes.Append(orderDate)

  Dim shipTo As XmlElement = PO.CreateElement("shipTo")
  purchaseOrder.AppendChild(shipTo)

  Dim country As XmlAttribute = PO.CreateAttribute("country")
  country.Value = "US"
  shipTo.Attributes.Append(country)

  ... 
Here is XLinq:

  New XElement("item", _
    New XAttribute("partNum", "926-AA"), _
    New XElement("productName", "Baby Monitor"), _
    New XElement("quantity", 1), _
    New XElement("price", 39.98), _
    New XElement("shipDate", "1999-05-21"))))

All the accidental complexity of DOM has been removed. Plus, VB 9 includes native XML syntax that makes XML data construction even simpler. While difficult to read, the SAX-based approach, however, is very efficient in that no document tree is constructed, since XML data is read and written as you go.

A new XStreamingElement object was introduced in the latest version of XLinq that suggests a possible approach to lazily construct an XML document for reading and writing using the power of iterators—an approach that may be able to compete with SAX-based approaches in memory usage and performance. In effect, a document tree no longer needs to be loaded and only one scan is perform. You can have the simplicity and naturalness of a functional API along with the efficiency of a traditional imperative approach.

Outstanding! I currently construct a document tree to load XML, HTML and RTF files, primarily for its reliability and simplicity, but also to provide a whole document perspective. This streaming technique suggests a more efficient implementation using iterators.

Comments

 

Navigation

Categories

About

Net Undocumented is a blog about the internals of .NET including Xamarin implementations. Other topics include managed and web languages (C#, C++, Javascript), computer science theory, software engineering and software entrepreneurship.

Social Media