2010-04-13 56 views
9

OK,隨機問題位存在的元素,但要做到這一點,最好的辦法就是剛纔添加的代碼,你就可以明白我的意思,立竿見影:C#檢查,同時使用LINQ to XML

XML:

<?xml version="1.0" encoding="utf-8" ?> 
<customers> 
    <customer> 
    <id>1</id> 
    <name>Blah-face</name> 
    <Type>1</Type> 
    </customer> 
    <customer> 
    <id>2</id> 
    <name>Blah-face-2</name> 
    <Type>2</Type> 
    </customer> 
    <customer> 
    <id>3</id> 
    <name>Blah-face-3</name> 
    <Type>1</Type> 
    <SuperType>1</SuperType> 
    </customer> 
</customers> 

C#:

XDocument linquee = XDocument.Load(path); 

var superType = (from c in linquee.Descendants("customer") 
       where (c.Element("SuperType").Value == "1") 
       select c).ToList(); 

這來了一個空的錯誤 - 我需要的 「父」 元素之前,用null值添加到每個客戶,或者是有一個解決方法,這將意味着我沒有 要做到這一點?

乾杯!

回答

13

試試這個:

var superType = (from c in from c in linquee.Descendants("customer") 
       where (string) c.Element("SuperType") == "1" 
       select c).ToList(); 

基本上如果你施放空XElement參考string,你會得到一個空引用(你可以用 「1」 比較)。

另一種方法是投給int?其中(IIRC)將返回元素是否缺少一個空int?值,但就甭想如果它的存在,但非數字:

var superType = (from c in from c in linquee.Descendants("customer") 
       where (int?) c.Element("SuperType") == 1 
       select c).ToList(); 
+0

完美,使事情比檢查空值更簡單。將在一會兒「打勾」。 – 2010-04-13 14:23:01

6

你應該能夠只需添加一個檢查NULL

where c.Element("SuperType") != null 
&& [your other criteria] 
3

您是否嘗試過檢查,如果SuperType元素試圖讀取它的價值之前存在?

... 
where (c.Element("SuperType") != null && c.Element("SuperType").Value == "1") 
... 
0

我會做像這樣:

var superType = linquee.Descendants("customer"). 
    Where(c => c.Element("SuperType") != null 
     && c.Element("SuperType").Value == "1"); 
0

也應該能夠清理這個還挺擴展,像東西了..

public string Element_valStr(XElement xElm, string xName) 
{ 
    if (xElm.Element(xName) == null) return string.empty; 
    return xElm.Element(xName).Value; 
} 

,然後只是:

var superType = (from c in linquee.Descendants("customer") 
        where (c.Element_valStr("SuperType") == "1") 
        select c).ToList(); 
0

我發現使用一個很好的解決方案的任何()結合有條件的經營者:

result = entry.Elements(ArbitraryElement).Any() ? (entry.Element(ArbitraryElement).Attributes(ArbitraryAttribute).Any() ? entry.Element(ArbitraryElement).Attribute(ArbitraryAttribute).Value : "-1") : "-1"

訣竅是與任何一起使用的元素() ()檢查元素是否存在(屬性()相同)

因此,對於此示例,它將是這樣的:

var superType = from c in linquee.Descendants("customer") 
       select c.Elements("SuperType").Any() ? c.Element("SuperType").Value : "0";