Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
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:
<customerid="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.”