首页 > 解决方案 > 如果人员 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 库。

谢谢你的帮助!

标签: c#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");

现场演示


推荐阅读