2014-09-24 69 views
0

属性我有一个这样的XML -Lambda表达式来选择XML

<root> 
    <child at1="1Dragon" at2="2"> 
     ... 
    </child> 
</root> 

我想查询AT1属性并检查它是否在字符串中有1个。为此,我写了这个lambda表达式 -

XDocument xml = XDocument.Parse(my_xml); 
bool test = xml.Descendants("child").Attributes("at1").ToString().Contains("1"); 

现在,这并没有给我想要的结果。属性列表确实有at1和at2,但我如何查询它们?

感谢

回答

2

所以您的查询的这部分返回子节点的属性的枚举,匹配名称“AT1”。

xml.Descendants("child").Attributes("at1") 

这个调用toString调用了IEnumerable的默认的ToString实现,这是不是你想要的。您需要调用LINQ扩展方法来遍历属性并检查任何属性的值是否匹配。 Any似乎是一个很好的匹配:

bool test = xml.Descendants("child").Attributes("at1").Any(attribute => 
    attribute.Value.Contains("1")); 
1

你不能为Attributes("at1").ToString();返回表示当前对象,它是一个IEnumerable<string> litteraly返回

如果你只有一个Child,你可以做这样的事情

字符串
bool testVallue = xml.Descendants("child").Attributes("at1").FirstOrDefault().Value.Contains("1"); 

如果你希望所有的孩子的所有属性,只是这样做

var allVallue = xml.Descendants("child").Attributes("at1").Where(att => att.Value.Contains("1")); 
//you can then check 
     if (allVallue.Any()) 
     { 

     }