2

我有以下代码:

static void Main(string[] args)
{
    XmlDocument xml = new XmlDocument();
    xml.Load(@"C:\MR.xml");
    XmlNodeList stations = xml.SelectNodes("//FileDump/Message/Attachment");
    var Message_ID = xml.SelectSingleNode("//FileDump/Message/MsgID").InnerXml;

    Console.WriteLine("Message ID is :{0}", Message_ID);

    foreach (XmlNode station in stations)
    {
        var File_Name = station.SelectSingleNode("FileName").InnerXml;
        var File_ID = station.SelectSingleNode("FileID").InnerXml;
    }
}

FileID 和 FileName 并不总是存在于某些文件中。在这种情况下如何避免 NullReferenceExceptions?

4

4 回答 4

1

您可以执行以下操作:

string FileName= "";
string File_ID = "";

if (station.SelectSingleNode("FileName") != null)
    File_Name = station.SelectSingleNode("FileName").InnerXml;
if (station.SelectSingleNode("FileID") != null)       
    File_ID = station.SelectSingleNode("FileID").InnerXml;

如果 vars 不是空字符串,则继续处理 ... ("") ...

于 2013-11-15T01:38:16.543 回答
1

如果必须在很多地方进行检查并保持代码简单明了,我会尝试这样的事情

public static class Helpers
{
   public static string GetInnerXml(this XmlNode node, string innerNodeName)
   {
     string innerXml = "";
     XmlNode innerNode = node.SelectSingleNode(innerNodeName);

     if (innerNode != null)
     {
       innerXml = innerNode.InnerXml;
     }

     return innerXml;
   }
}

并像这样使用它

  static void Main(string[] args)
  {
    XmlDocument xml = new XmlDocument();
    xml.Load(@"C:\MR.xml");
    XmlNodeList stations = xml.SelectNodes("//FileDump/Message/Attachment");
    var Message_ID = xml.GetInnerXml("//FileDump/Message/MsgID");

    Console.WriteLine("Message ID is :{0}", Message_ID);

    foreach (XmlNode station in stations)
    {
      var File_Name = station.GetInnerXml("FileName");
      var File_ID = station.GetInnerXml("FileID");
    }
  }
于 2013-11-15T01:56:20.560 回答
0
static void Main(string[] args)
{
    XmlDocument xml = new XmlDocument();
    xml.Load(@"C:\MR.xml");
    XmlNodeList stations = xml.SelectNodes("//FileDump/Message/Attachment");
    var Message_ID = xml.SelectSingleNode("//FileDump/Message/MsgID").InnerXml;

    Console.WriteLine("Message ID is :{0}", Message_ID);

    foreach (XmlNode station in stations)
    {
        var fileNameNode = station.SelectSingleNode("FileName");
        var fileIdNode = station.SelectSingleNode("FileID");

        var File_Name = fileNameNode == null ? (string)null : fileNameNode.InnerXml;

        var File_ID = fileIdNode == null ? (string)null : fileIdNode.InnerXml;;
    }
}
于 2013-11-15T02:35:12.673 回答
0

我通常使用扩展方法来处理意外的空值

public static string GetValueIfNotNull(this XmlAttribute xmlAttribute)
{
  if (xmlAttribute == null)
    {
      return null;
    }
  return xmlAttribute.Value;
}

那我可以做myElement.Attribute("someAttribute").GetValueIfNotNull();

于 2013-11-15T06:49:23.157 回答