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:
<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.”
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access