【问题标题】:How to check if xElement value exists?如何检查 xElement 值是否存在?
【发布时间】:2016-12-14 15:26:18
【问题描述】:

例如,我需要检查“Charrizard”是否存在,我在网上四处寻找,但只找到了 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.)..

【问题讨论】:

    标签: c# xml linq xelement


    【解决方案1】:
    bool b =  doc.Descendants("name").Any(x=> x.Value == "Charrizard");
    

    您可以使用Enumerable.Any 实现这一目标

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

    这里是dotNetFiddle的完整示例

    【讨论】:

    • 在'x => x.Value'中,'x'代表'name'?
    • @tomyforever 因此使用 doc.Descendants("name") 获取文档的所有 XElement 并将其放入 IEnumerable 集合中。如果您调用 doc.Descendants("name").ToList() 这将创建 List 与 TagName 名称。我引用的任何类似方法确定序列的任何元素是否满足条件。所以我的条件是来自 IEnumerable 的任何元素的值(所以节点值)等于 Charrizard 如果不返回 false,则返回 true。您可能也应该阅读什么是 lambda 表达式:msdn.microsoft.com/en-us/library/bb397687.aspx
    • @tomyforever 如果对您有帮助,您可以将问题标记为正确
    猜你喜欢
    • 1970-01-01
    • 2011-03-22
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 2011-01-27
    相关资源
    最近更新 更多