Information Technology Reference
In-Depth Information
Getting the third planet would be simply using an indexer:
// gets the third planet (Earth)
dynamic
test3 = dynamicXML[
"Planet"
,
2
];
Reaching the moons becomes two chained indexers:
dynamic
earthMoon = dynamicXML[
"Planet"
,
2
][
"Moons"
,
0
].Moon;
Finally, because it's dynamic, you can define the semantics so any missing
node returns an empty element. That means all of these would return
empty dynamic XElement nodes:
dynamic
test6 = dynamicXML[
"Planet"
,
2
]
[
"Moons"
,
3
].Moon;
// earth doesn't have 4 moons
dynamic
fail = dynamicXML.NotAppearingInThisFile;
dynamic
fail2 = dynamicXML.Not.Appearing.In.This.File;
Because missing elements will return a missing dynamic element, you can
continue to dereference it and know that if any element in the composed
XML navigation is missing, the final result will be a missing element.
Building this is another class derived from DynamicObject. You have to
override TryGetMember, and TryGetIndex to return dynamic elements
with the appropriate nodes.
public class
DynamicXElement
:
DynamicObject
{
private readonly
XElement
xmlSource;
public
DynamicXElement(
XElement
source)
{
xmlSource = source;
}
public override bool
TryGetMember(
GetMemberBinder
binder,
out object
result)
{
result =
new
DynamicXElement
(
null
);
if
(binder.Name ==
"Value"
)
{
result = (xmlSource !=
null
) ?
xmlSource.Value :
""
;
return true
;
}