2010-04-13 58 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";