Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm parsing XML. I normally parse it the way I show in the code below which is straightforward The problem is that I don't own the XML I'm parsing and I can't change it. Sometimes there is no thumbnail element (there are no tags) and I get an Exception.

Is there a way to maintain this simplicity and check if the element exists? Or do I have to get first an XElement list with LINQ, to then check it and fill only the existing object properties?

void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    XDocument dataDoc = XDocument.Load(new StringReader(e.Result));

    var listitems = from noticia in dataDoc.Descendants("Noticia")
                    select new News()
                    {
                        id = noticia.Element("IdNoticia").Value,
                        published = noticia.Element("Data").Value,
                        title = noticia.Element("Titol").Value,
                        subtitle = noticia.Element("Subtitol").Value,
                        thumbnail = noticia.Element("Thumbnail").Value
                    };

    itemList.ItemsSource = listitems;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
185 views
Welcome To Ask or Share your Answers For Others

1 Answer

[Edit]Jon Skeet's answer should be the accepted answer. It is far more readable and easier to apply.[/edit]

Create an extension method like this :

public static string TryGetElementValue(this XElement parentEl, string elementName, string defaultValue = null) 
{
    var foundEl = parentEl.Element(elementName);

    if (foundEl != null)
    {
        return foundEl.Value;
    }

    return defaultValue;
}

then, change your code like this :

select new News()
{
    id = noticia.TryGetElementValue("IdNoticia"),
    published = noticia.TryGetElementValue("Data"),
    title = noticia.TryGetElementValue("Titol"),
    subtitle = noticia.TryGetElementValue("Subtitol"),
    thumbnail = noticia.TryGetElementValue("Thumbnail", "http://server/images/empty.png")
};

This approach allows you to keep a clean code with isolating the check of element presence. It also allow you to define a default value, which can be helpful


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...