views:

294

answers:

2

Hi, in a ASP.NET application (MVC) I have a foreach loop that loops through a structure that may contain or not some element:

        <% foreach (XElement segnalazione in ((XElement)ViewData["collezioneSegnalazioni"]).Elements("dossier")) { %>

            <tr>

                <td><%= Html.Encode(segnalazione.Element("NUM_DOSSIER").Value) %></td>
                <td><%= Html.Encode(segnalazione.Element("ANAG_RAGSOC_CGN").Value) %></td>
                <td><%= Html.Encode(segnalazione.Element("ID_RIFATT_SEGN0").Value) %></td>
                <td><%= Html.Encode(segnalazione.Element("FLG_STATUS").Value) %></td>
                <td><%= Html.Encode(segnalazione.Element("DT_ACCADIMENTO").Value)%></td>
                <td><%= Html.Encode(segnalazione.Element("COD_RAMO_LUNA").Value) %></td>
            </tr>
        <% } %>

Now, I get a NullReferenceException when Element("DT_ACCADIMENTO") is not set within the XElement. Is there a quick way to handle this? I tried with

<td><%= Html.Encode(segnalazione.Element("DT_ACCADIMENTO").Value ?? "")%></td>

but it does not work as, I guess, it checks if Value is null, where I have a problem with the field itself. Any help appriciated

+3  A: 
<td><%= Html.Encode((string)segnalazione.Element("DT_ACCADIMENTO") ?? "")%></td>
Mehrdad Afshari
Explicit Operator for XElement to string cast (http://msdn.microsoft.com/en-us/library/bb155263.aspx)
Joseph
+1  A: 

Try using:

segnalazione.Element("NUM_DOSSIER") == null ? "" : segnalazione.Element("NUM_DOSSIER").Value
Ronald Wildenberg
You'd be querying the XElement object twice, which might harm performance in case there's a lot of child elements, and I don't think it has any advantage over the plain approach in LINQ to XML. Don't you think?
Mehrdad Afshari
You're absolutely right and I think your solution is better. Not sure why I'm getting all the votes ;-)
Ronald Wildenberg
Mehrdad's solution doesn't encode the Value property. Does the Element output it's Value property when the toString is called? If not then I would think that would be an incorrect implementation.
Joseph
@Joseph: The cast will return null if the element is `null` and Value if it's not null. `ToString` is irrelevant here. It's using an explicit operator string(XElement) that's defined for XElement.
Mehrdad Afshari
@Mehrdad Oh I see. Very cool! +1 I didn't notice the explicit operators (http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.op_explicit.aspx)
Joseph
In fact, these operators are the standard methods in LINQ to XML (specially in `where` clauses). Without them the queries will be pretty ugly.
Mehrdad Afshari