C# 如何确定 XElement.Elements() 是否包含具有特定名称的节点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/239951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:23:50  来源:igfitidea点击:

How to determine if XElement.Elements() contains a node with a specific name?

c#xmllinq.net-3.5

提问by Malik Daud Ahmad Khokhar

For example for the following XML

例如对于以下 XML

 <Order>
  <Phone>1254</Phone>
  <City>City1</City>
  <State>State</State>
 </Order>

I might want to find out whether the XElement contains "City" Node or not.

我可能想知道 XElement 是否包含“城市”节点。

采纳答案by Amy B

Just use the other overload for Elements.

只需为Elements使用其他重载。

bool hasCity = OrderXml.Elements("City").Any();

回答by James Curran

It's been a while since I did XLinq, but here goes my WAG:

自从我做 XLinq 已经有一段时间了,但我的 WAG 来了:

from x in XDocument
where x.Elements("City").Count > 0
select x

;

;

回答by Mark

David's is the best but if you want you can write your own predicate if you need some custom logic OrderXML.Elements("City").Exists(x=>x.Name =="City")

David's 是最好的,但如果您需要一些自定义逻辑,您可以编写自己的谓词 OrderXML.Elements("City").Exists(x=>x.Name =="City")