如何检查node的值,我想在xml中读取它

如何检查node的值,我想在xml中读取它,xml,c#-4.0,Xml,C# 4.0,我的程序正在从xml读取值。问题是,有时xml中会出现一些值,而有时xml中不会出现这些值。当时,对象引用未设置为对象的瞬间错误消息。因此,我希望如果xml中不存在该值,那么我不希望将该值赋给任何变量。下面是我的代码供您审阅 foreach (XElement AddressNode in ActivityLocationNode.Elements("Address")) { activitylocationtype.Address.City = AddressNode.Element

我的程序正在从xml读取值。问题是,有时xml中会出现一些值,而有时xml中不会出现这些值。当时,对象引用未设置为对象的瞬间错误消息。因此,我希望如果xml中不存在该值,那么我不希望将该值赋给任何变量。下面是我的代码供您审阅

foreach (XElement AddressNode in ActivityLocationNode.Elements("Address"))
  {
   activitylocationtype.Address.City = AddressNode.Element("City").Value;
   activitylocationtype.Address.CountryCode = AddressNode.Element("CountryCode").Value;
   activity.ActivityLocation = activitylocationtype;
   activitylist.Add(activity);
   pakagetype.Activity = activitylist;
   pakagetypelist.Add(pakagetype);
   shipment.Package = pakagetypelist;
   shipmentlist.Add(shipment);
   trackresponse.Shipment = shipmentlist; }
下面是我正在阅读的xml

<Address>

  <CountryCode>GB</CountryCode>
</Address>

国标

在代码中,国家代码即将到来,但我首先阅读的是城市代码。所以这里我得到了错误。感谢您的评论。

您可以将其强制转换为
字符串以避免异常,而不是访问
XElement
Value
属性,例如:

//this will give you null because <City> is not found, and no exception
activitylocationtype.Address.City = (string)AddressNode.Element("City");
activitylocationtype.Address.CountryCode = (string)AddressNode.Element("CountryCode");
//这将为您提供null,因为找不到,并且没有异常
activitylocationtype.Address.City=(字符串)AddressNode.Element(“城市”);
activitylocationtype.Address.CountryCode=(字符串)AddressNode.Element(“CountryCode”);

只需在赋值之前检查
AddressNode.Element(“城市”)
是否为空