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 ...

Get LINQ Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.