Information Technology Reference
In-Depth Information
var xml = createXML();
var firstPlanet = xml.Element( "Planet" );
That's not too bad, but the farther you get into the file, the more compli-
cated the code gets. Getting Earth (the third planet) looks like this:
var earth = xml.Elements("Planet").Skip(2).First();
Getting the name of the third planet is more code:
var earthName = xml.Elements( "Planet" ).Skip( 2 ).
First().Element( "Name" );
Once you're getting moons, it's really long code:
var moon = xml.Elements( "Planet" ).Skip( 2 ).First().
Elements( "Moons" ).First().Element( "Moon" );
Furthermore, the above code only works if the XML contains the nodes
you're seeking. If there was a problem in the XML file, and some of the
nodes were missing, the above code would throw an exception. Adding the
code to handle missing nodes adds quite a bit more code, just to handle
potential errors. At that point, it's harder to discern the original intent.
Instead, suppose you had a data-driven type that could give you dot nota-
tion on XML elements, using the element name. Finding the first planet
could be as simple as:
// Create an XElement document containing
// solar system data:
var xml = createXML();
Console .WriteLine(xml);
dynamic dynamicXML = new DynamicXElement (xml);
// old way:
var firstPlanet = xml.Element( "Planet" );
Console .WriteLine(firstPlanet);
// new way:
// returns the first planet.
dynamic test2 = dynamicXML.Planet;
Search WWH ::




Custom Search