【问题标题】:C# xmlTextReader error if element doesn't exist如果元素不存在,C# xmlTextReader 错误
【发布时间】:2012-11-29 09:33:15
【问题描述】:

我正在尝试使用 xmlTextReader 读取 xml 文件并将其存储在列表中,但我正在努力克服这个烦人的小错误。让我再解释一下:

我将文件中的所有节点存储在 XmlNodeList 中,并使用 foreach 循环读取每个节点并使用此类模板将其添加到我的列表中:

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

这里是主要代码:

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
            });
        }  

代码工作正常,直到第三个 xml 元素,其中缺少“ReleaseDate”节点。它只是没有。所以抛出一个错误。

我知道我需要想办法在读取节点之前检查它是否存在,但是我有点搞砸了;到目前为止,没有任何事情是成功的。有没有人有任何想法?谢谢。

【问题讨论】:

  • 人们已经给出了很好的答案,但为了将来的参考,请始终具体说明您遇到的错误。 “抛出错误”比“在标记的行中抛出 NullReferenceException”或类似的东西要少得多。异常有不同的风格正是因为它们可以帮助您调试问题,所以如果您需要帮助,请随时分享它们! ;-)
  • @Bagshot 我已经更新了我的答案。也许对你有用。

标签: c# xml xmltextreader


【解决方案1】:

尝试检查是否为空:

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

编辑:

我想使用的其他方法是向您的类添加 XML 属性:

[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; }
}

此重构将允许您使用XmlSerializer.Deserialize(示例部分)方法并自动将 XML 映射到您的类。

【讨论】:

    【解决方案2】:

    在访问任何属性之前检查对象是否为空。

    release = xn["ReleaseDate"] != null ? xn["ReleaseDate"].InnerXml : string.Empty
    

    【讨论】:

      【解决方案3】:

      你可以做一个扩展方法,比如

       public static T GetXmlValue<T>(this XmlNode node, string name, T defaultValue)
          {
              if (node != null && node[name] != null)
              {
                  if (typeof(T) == typeof(string))
                  {
                      return (T)(object)node[name].InnerText;
                  }
                  else if (typeof(T) == typeof(int))
                  {
                      int value = 0;
                      if (int.TryParse(node[name].InnerText, out value))
                      {
                          return (T)(object)value;
                      }
                  }
              }
              return defaultValue;
          }
      

      用法:

      list.Add(new getGamesList()
      {
          id = xn.GetXmlValue<int>("id", 0),
          title = xn.GetXmlValue<string>("GameTitle", string.Empty),
          release = xn.GetXmlValue<string>("ReleaseDate", string.Empty),
          platform = xn.GetXmlValue<string>("Platform", string.Empty)
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-03
        相关资源
        最近更新 更多