2016-12-14 157 views
1

我需要检查例如'Charrizard'是否存在,我在网上查找,但只发现xElement属性值和子节点的例子。如何检查xElement值是否存在?

<pokemons> 
    <pokemon> 
    <color>red</color> 
    <name>Charrizard</name> //the content is named value right ?? 
    </pokemon> 
</pokemons> 

我看到它的地方开始,如:

XDocument doc = XDocument.Load("pokemons.xml"); 
bool b = doc.Descendants(but don't know how to access the value.).. 

回答

2
bool b = doc.Descendants("name").Any(x=> x.Value == "Charrizard"); 

您实现,使用Enumerable.Any

确定序列中的任何元素是否满足条件。

在这里,在dotNetFiddle

+0

完整的例子非常感谢你:) – tomyforever

+0

在 'X => x.Value', 'X' 代表 '名'? – tomyforever

+0

@tomyforever所以使用doc.Descendants(“name”)将文档的所有XElement放入IEnumerable集合中。如果你调用doc.Descendants(“name”)。ToList()这将创建带有TagName名称的List 。任何像我引用的方法确定序列中的任何元素是否满足条件。所以我的条件是来自IEnumerable 的任何元素具有Value(所以节点值)等于Charrizard返回true如果不返回false。您应该也许应该阅读什么是lambda表达式:https://msdn.microsoft.com/en-us/library/bb397687.aspx – mybirthname