0

我试图从值不以某些文本开头的 xml 文件中获取所有属性值

我有这个代码

IEnumerable<XElement> elements =
    (from el in xmlFile.Root.Elements(elementName)
     where (string)el.Attribute(attributeName)  !StartWith("abc")
     select el);

我怎样才能解决这个问题

4

2 回答 2

2

您需要使用有效的表达式,例如

where !el.Attribute(attributeName).Value.StartsWith("abc")

重要的是要了解进入 LINQwhere子句的内容不是“魔术”语法 - 它只是一个普通表达式,它可以使用查询表达式声明的范围变量el(在这种情况下)。所以你应该问自己,“如果我不是在 LINQ 中编写的,并且我有一个变量称为el引用元素,我将如何编写一个if条件来检查属性值不是以 开头abc?”

(当属性可能丢失并且我只想得到一个空值时,我使用显式转换,但是在这种情况下,无论如何当属性丢失时你都会崩溃,你只需要字符串值,所以你可以好好利用Value物业。)

请注意,由于您在这里只有一个where子句(和一个微不足道的select),因此使用非查询表达式形式可能更具可读性:

var elements = xmlFile.Root.Elements(elementName)
                      .Where(el => !el.Attribute(attributeName).Value.StartsWith("abc"));
于 2012-07-25T08:15:29.630 回答
0

试试这个(调整你的开始)

IEnumerable<XElement> elements = 

from el in xmlFile.Root.Elements(elementName) 
where ! el.Attribute(attributeName).Value.StartWith("abc") 
select el;
于 2012-07-25T08:16:17.630 回答