Search code examples
c#xmlxmltextreader

C# xmlTextReader error if element doesn't exist


I'm trying to read an xml file using xmlTextReader and store it in a list, but I 'm struggling to overcome this annoying little error. Let me explain a bit more:

I'm storing all the nodes from the file in an XmlNodeList, and using a foreach loop to read each node and add it to my list using this class template:

public class getGamesList
{
    public int id { get; set; }
    public string title { get; set; }        
    public string release { get; set; }        
    public string platform { get; set; }
}

Here is the main code:

List<getGamesList> list = new List<getGamesList>();
        String URLString = "http://thegamesdb.net/api/GetGamesList.php?name="+name;
        XmlTextReader tr = new XmlTextReader(URLString);

        XmlDocument xml = new XmlDocument();
        xml.Load(tr);
        XmlNodeList xnList = xml.SelectNodes("/Data/Game");

        foreach (XmlNode xn in xnList)
        {
            list.Add(new getGamesList()
            {
                id = Convert.ToInt32(xn["id"].InnerText),
                title = xn["GameTitle"].InnerText,
                release = xn["ReleaseDate"].InnerXml,
                platform = xn["Platform"].InnerText
            });
        }  

The code works fine up until the 3rd xml element, where there is a missing "ReleaseDate" node. It just doesn't have one. So an error is thrown.

I know I need to work out a way of checking if the node exists before I read it, but I'm getting in a bit of a mess; nothing so far has been successful. Does anyone have any ideas? Thanks.


Solution

  • Try to check for null:

    release = (null != xn["ReleaseDate"]) ? xn["ReleaseDate"].InnerXml : "",
    

    EDIT:

    Other way I would like to use is to add an XML attributes to your class:

    [Serializable]
    public class getGamesList
    {
        [XmlElement("...")]
        public int id { get; set; }
        [XmlElement("...")]
        public string title { get; set; }        
        [XmlElement("ReleaseDate")]
        public string release { get; set; }        
        [XmlElement("...")]
        public string platform { get; set; }
    }
    

    This refactoring will allow you to use XmlSerializer.Deserialize (Example section) method and map XML to your class automatically.