I am receiving data from a Web Service. The XML coming in is something like:
<data>
<item>
<code>a</code>
<price>2.89</price>
</item>
<item>
<code>a</code>
<price>2.89</price>
<colour>blue</colour>
</item>
</data>
So, we see that one item has an additional property of Colour.
Okay, this gets converted into a List<item> which is the point at which I get hold of it.
I need to convert this list into an XDocument.
Using:
var xml = new XDocument(
new XDeclaration("1.0", "utf-16", "yes"),
new XElement("data",
from i in myList
select new XElement("item",
new XElement("price", i.price),
new XElement("code", i.code),
new XElement("colour", i.colour))));
(I’ve typed this from memory, so excuse spellings)
Here, it errors because i.colour is null.
How do I cope with this?
Thanks in advance
Griff
You’ll want to check whether i.colour is
nullbefore trying to access it.You can do this neatly using the null-coalescing operator like:
Assuming that you want an empty string as the value if
i.colourisnull.UPDATE
Based on your comment below, if you don’t want the element added if
i.colouris null then create it independantly of theXDocumentinstantiation and add it as required.}