问题描述:

I have the following code:

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 and FileName do not always exist in some files. How can I avoid NullReferenceExceptions in this case?

网友答案:

I would try to something like this if that check has to happen in lot of places and to keep the code simple and clear

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

and use it like this

  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");
    }
  }
网友答案:

You could do something like:

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;

And continue processing if the vars are not the empty string ... ("") ...

网友答案:
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;;
    }
}
网友答案:

I usually use extension methods for handling unexpected nulls.

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

Then I can do myElement.Attribute("someAttribute").GetValueIfNotNull();

相关阅读:
Top