我想在那裏值不使用一些文本的LINQ to XML!StartWith
我有這樣的代碼
IEnumerable<XElement> elements =
(from el in xmlFile.Root.Elements(elementName)
where (string)el.Attribute(attributeName) !StartWith("abc")
select el);
開始得到xml文件的所有屬性值我怎樣才能解決這個
我想在那裏值不使用一些文本的LINQ to XML!StartWith
我有這樣的代碼
IEnumerable<XElement> elements =
(from el in xmlFile.Root.Elements(elementName)
where (string)el.Attribute(attributeName) !StartWith("abc")
select el);
開始得到xml文件的所有屬性值我怎樣才能解決這個
您需要使用有效的表達式,例如
where !el.Attribute(attributeName).Value.StartsWith("abc")
明白什麼進入一個LINQ where
條款是非常重要的不是「魔術」語法 - 它只是一個普通的表達,這可以使用查詢表達式(el
在這個聲明的範圍變量案件)。所以你應該問自己:「如果我不是在LINQ中寫這個,而且有一個變量叫el
是指一個元素,我怎麼會寫一個if
條件來檢查屬性值是不是以abc
開頭? 「 (我使用明確的轉換時,該屬性可以丟失,我想只是得到一個null,但在這種情況下,你會去當屬性的東西丟失,而且你只是想要的字符串值,所以你不妨使用Value
屬性。)
注意,因爲你已經只得到了where
條款這裏(和瑣碎select
),很可能會更具可讀性使用非查詢表達形式:
var elements = xmlFile.Root.Elements(elementName)
.Where(el => !el.Attribute(attributeName).Value.StartsWith("abc"));
試着用硫s(調整你的startwith)
IEnumerable<XElement> elements =
from el in xmlFile.Root.Elements(elementName)
where ! el.Attribute(attributeName).Value.StartWith("abc")
select el;
我得到這個錯誤: 對象引用未設置爲對象的實例。 \t 它工作正常的另一種情況爲: 其中(字符串)el.Attribute(attributeName)!= attributeValue select el – Maro 2012-07-25 08:29:07
@Maro:那麼表明你有一個沒有該屬性的元素... – 2012-07-25 11:07:06