そこにない可能性のあるサブツリーの下にある xml タグの値を取得しようとすると、nullexception の問題が発生します。
拡張ハンドラは、既存のサブツリーでタグが見つからない場合はうまく機能しますが、存在しないサブツリーでタグを探す場合は処理できないようです。
この場合、サブツリーは summaryData であり、そこにある場合とない場合があり、addressLine1 を取得しようとすると、null
.
System.NullReferenceException が発生しました。メッセージ = オブジェクト参照がオブジェクトのインスタンスに設定されていません。
これが 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;
}
}
サブツリーが存在しないときに失敗する理由がわからないので、助けていただければ幸いです。