views:

50

answers:

1

I want to use LINQ to XML in Silverlight 3 since there is no XPath support. I have kind of got the hang of it. But the project I'm working on will not guarantee that all the XML tags I will be querying for will appear in the result XML file.

Due to this I will not be able to query the overall file as XDocument becase the absence of the tag in one document will jumble up the enumeration. Is there anyway to typecast an XNode to XDocument? I am asking this as I am not able to query the XNode.

+2  A: 

Even with LINQ-to-XML you should be querying by name, so I'm not sure why the absence of any particular tag should "jumble up the enumeration" - simply; you might have some nulls, i.e.

var customer = node.Element("Foo");
// now test for null ;p

You can't cast an arbitrary XNode to an XDocument, but if you are sure it is an element, casting to XElement should provide what you need.

Note also that when value nodes may be missing, you might find it easiest to use the conversion operators:

var auditDate = (DateTime?)e.Element("AuditDate");

if <AuditDate> doesn't exist, this will return an empty Nullable<DateTime> - same approach works for most common value-types, or for strings just convert to string.

Marc Gravell