C# 使用“时出现NullReferenceException”;不是StartWith“;林克
我试图删除所有属性值不是以特定文本开头的元素 多亏了Jon Skeet,我得到了第一部分,但是有些元素不包含此属性,因此我得到了带有消息的C# 使用“时出现NullReferenceException”;不是StartWith“;林克,c#,linq,C#,Linq,我试图删除所有属性值不是以特定文本开头的元素 多亏了Jon Skeet,我得到了第一部分,但是有些元素不包含此属性,因此我得到了带有消息的NullReferenceExpection:“对象引用未设置为对象的实例” 我为null值添加了一个额外的检查,但它仍然不起作用 elements =(from el in xmlFile.Root.Elements(elementName) where ( !el.Attribute(attributeName).Value.Equals(DBNull.V
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);
对
null
属性调用Equals
会触发异常。没有必要(事实上,这是不正确的)将XAttribute
的值与DBNull
进行比较,因为LINQ2XML对缺少的属性使用“plain”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);
对
null
属性调用Equals
会触发异常。没有必要(事实上,这是不正确的)将XAttribute
的值与DBNull
进行比较,因为LINQ2XML对缺少的属性使用“plain”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);
在测试属性之前,必须测试节点是否包含该属性 添加
el.attributeName(属性名称)!=空
:
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);
在测试属性之前,必须测试节点是否包含该属性 添加
el.attributeName(属性名称)!=空
:
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);