I have an XML document that I am parsing that does not follow any kind of fixed schema. I need to parse out values by doing something like this:
invoiceDetail.PartNO = invoiceLine.Element(ns + "Item").Element(ns + "ItemID").Element(ns + "ID").Value;
In this example, invoiceLine is of XElement type. The issue is that some nodes do not always exist and in those cases I would prefer to return null or empty instead of returning an error. Is there any way to do this currently or should I just make a special function myself that takes a namespace and a list of element names to attempt to parse into?
XLINQ already does this.
.Element()will returnnullif there is no element with that name.To avoid repetitive null checks, use
.Elements()instead:Each
Elements()call will return anIEnumerable<XElement>. If there aren’t any matching elements, it will return an empty sequence, and the rest of the code will still work..SingleOrDefault()will convert the final sequence to a single element ornull.The
(string)cast calls a custom explicit conversion which should returnnullif the element was null. You can similarly cast directly to basic value types.