1

特定のテキストで始まらない属性値を持つすべての要素を削除しようとしています

Jon Skeetのおかげで最初の部分を取得しましたが、一部の要素にこの属性が含まれていないため、NullReferenceExpection「オブジェクト参照がオブジェクトのインスタンスに設定されていません」というメッセージが表示されました。

null値のチェックを追加しましたが、それでも機能しませんか?

elements =(from el in xmlFile.Root.Elements(elementName)
where ( !el.Attribute(attributeName).Value.Equals(DBNull.Value)
&& !el.Attribute(attributeName).Value.StartsWith(searchBeforeStar))
select el);
4

2 に答える 2

3

属性を呼び出すEqualsnull、例外がトリガーされます。XAttributeの値をと比較する必要はありません (実際には正しくありません) DBNull。LINQ2XML はnull欠落している属性に対して「プレーン」を使用するためです。

これを試して:

elements =(from el in xmlFile.Root.Elements(elementName) where (
    el.Attribute(attributeName) != null &&
    el.Attribute(attributeName).Value != null && 
    !el.Attribute(attributeName).Value.StartsWith(searchBeforeStar)
)select el);
于 2012-07-25T12:32:57.717 に答える
2

テストする前に、ノードに属性が含まれているかどうかをテストする必要があります。

追加el.Attribute(attributeName) != null

elements =(from el in xmlFile.Root.Elements(elementName) 
           where ( el.Attribute(attributeName) != null
                && !el.Attribute(attributeName).Value.Equals(DBNull.Value) 
                && !el.Attribute(attributeName).Value.StartsWith(searchBeforeStar))
           select el);
于 2012-07-25T12:34:34.063 に答える