O'Reilly logo

LINQ Pocket Reference by Joseph Albahari, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Instantiating an X-DOM

Rather than use the Load or Parse methods, you can build an X-DOM tree by manually instantiating objects and adding them to a parent via XContainer ’s Add method.

To construct an XElement and XAttribute, you simply provide a name and value:

	XElement lastName = new XElement ("lastname", "Bloggs");
	lastName.Add (new XComment ("nice name"));

	XElement customer = new XElement ("customer");
	customer.Add (new XAttribute ("id", 123));
	customer.Add (new XElement ("firstname", "Joe"));
	customer.Add (lastName);

	Console.WriteLine (customer.ToString());

The result:

	<customer id="123">
	  <firstname>Joe</firstname>
	  <lastname>Bloggs<!--nice name -></lastname>
	</customer>

A value is optional when constructing an XElement—you can provide just the element name and add content later. Notice that when we did provide a value, a simple string sufficed— we didn’t need to explicitly create and add an XText child node. The X-DOM does this work automatically, so you can deal simply with “values.”

Functional Construction

In our preceding example, it’s hard to glean the XML structure from the code. X-DOM supports another mode of instantiation called functional construction (from functional programming). With functional construction, you build an entire tree in a single expression:

	XElement customer =
	  new XElement ("customer", new XAttribute("id", 123),
	    new XElement ("firstname","joe"),
	    new XElement ("lastname","bloggs",
	      new XComment ("nice name")
	    )
	  );

This has two benefits. First, the code resembles ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required