尝试获取一个可能不存在的子树下的xml标签值时,我遇到了nullexception问题。
当扩展处理程序在现有子树上找不到标签时,它运行良好,但似乎无法处理在不存在子树中寻找标签的情况。
在这种情况下,子树是summaryData,可能存在也可能不存在,而尝试获取addressLine1是它无法处理的null
,导致错误:
System.NullReferenceException发生,Message=Object reference not set to an instance of an object.
以下是xml,为了清晰起见进行了删减,但结构是正确的:
<record>
<accounts>
<account >
</account >
</accounts>
<summaryData>
<Date>2013-02-04</Date>
<address >
<city>Little Rock</city>
<postalCode>00000</postalCode>
<state>AR</state>
<addressLine1>Frank St</addressLine1>
</serviceAddress>
</summaryData>
</record>
我的C#代码如下:
xmlDoc.Descendants("account")
//select (string)c.Element("account") ;
select new
{
//this works fine
Stuffinxml = c.Element("stuffinxml").Value,
//this field may not be there, but the handler handlers the exception correctly here when it as the correct root (account)
otherstuff = CustXmlHelp.GetElementValue(mR.Element("otherstuff")),
//this is the problem, where the summaryData root does not exist (or moved somewhere else)
street_address = GetElementValue(c.Element("summaryData").Element("serviceAddress").Element("addressLine1"))
};
我的处理null的扩展方法如下:
public static string GetElementValue(this XElement element)
{
if (element != null)
{
return element.Value;
}
else
{
return string.Empty;
}
}
如果子树不存在,我不明白为什么会失败,希望能得到任何帮助。
address
标签 - 是打字错误还是实际记录? - Kami