c# - 如果人员 XML 列表中存在具有特定姓名的人员
问题描述
如何找出结果:
<People>
<Person name="John" />
<Person name="Andrew" />
</People>
我需要查明人员列表中是否存在具有特定姓名的人员。
例子:
if (Element("People").ForAny(person => person.name == "John")) // Returns True
if (Element("People").ForAny(person => person.name == "Amanda")) // Returns False
我正在使用 Xml Linq 库。
谢谢你的帮助!
解决方案
您可以简单地从根元素 People
导航。
在其所有后代 Person
中,是否有任何属性 name
等于您正在寻找的值:
string input = @"<People>
<Person name=""John"" />
<Person name=""Andrew"" />
</People>";
XDocument doc = XDocument.Parse(input);
var isJohnHere = doc.Element("People")
.Descendants("Person")
.Any(x=> x.Attribute("name").Value == "John");
List<string>
获取people's的相同方法name
将是:
var names = doc.Element("People")
.Descendants("Person")
.Select(x=> x.Attribute("name").Value);
甚至更短的“Person
无论在哪里,所有的 s”:
var isJohnHere2 = doc.Descendants("Person")
.Any(x=> x.Attribute("name").Value == "John");
推荐阅读
- apache-spark - 在内部使用 Kafka 独立执行 Spark 时出错
- android - Android - OpenCVLoader.initAsync 运行异常
- javascript - jquery 简单项目滑块
- c# - 在即发即弃的方法中等待
- servlets - 替换外部图片网址
- c++ - 如何读写 Qt 集合类
- flowtype - 静态方法中返回的类实例与类型不匹配
- c# - 循环遍历字符串数组以创建这些字符串的类变量
- java - FoundationDB 如何处理冲突事务?
- spring-cloud - 如何在 Spring Cloud Gateway 中为 IOExceptions 配置重试?