0

単純なxmlがあります。

        var FieldsInData = from fields in xdoc.Descendants("DataRecord")
                           select fields;

これで、FildsInDataにn個の異なるXElementアイテムがあります。

        foreach (var item in FieldsInData)
        {
            //working
            String id = item.Attribute("id").Value;
            //now i get a nullReferenceException because that XElement item has no Attribute called **fail**
            String notExistingAttribute = item.Attribute("fail").Value;
        }

その失敗属性を使用すると、nullReferenceExceptionが発生します。これは、存在しないためです。ある場合とそうでない場合があります。どうすればそれを優雅に処理できますか?

value.SingleOrDefault();を使用してみました。しかし、CharのIEnumerableであるため、別の例外が発生します。

4

2 に答える 2

2

これを行う別の方法を追加するために、null チェックに拡張メソッドを悪用することもできます。

public static class XmlExtensions 
{
    public static string ValueOrDefault(this XAttribute attribute) 
    {
        return attribute == null ? null : attribute.Value;
    }
}

そして、そのように使用します:

string notExistingAttribute = item.Attribute("fail").ValueOrDefault();
于 2012-08-17T13:22:38.140 に答える
0

以下を確認するだけですnull

String notExistingAttribute = "";

var attribute =  item.Attribute("fail");
if(attribute != null)
    notExistingAttribute = attribute.Value;
于 2012-08-17T13:17:41.930 に答える