c# - Linq to XML 获取一对多元素名称和属性名称/值

标签 c# linq-to-xml

我的 XML 如下所示:

<manager firstName="Dat" lastName="Bossman">
   <employee firstName="Jonathan" lastName="Smith" preferredName="Jon" />
   <employee christianName="Jane" lastName="Doe" />
   <employee lastName="Jones" firstInitial="A" middleName="J" />
</manager>

我想返回所有元素名称/属性名称/属性值组合的集合/列表,其中属性名称位于 { "firstName", "preferredName", "christianName", "firstInitial", “中间名”}

鉴于上面的 XML,我会得到一个如下所示的列表:

elementName  attributeName  attributeValue
============ ============== ===============
manager      firstName      Dat
employee     firstName      Jonathan
employee     preferredName  Jon
employee     christianName  Jane
employee     firstInitial   A
employee     middleName     J

下面有一些 LINQ,它返回正确的元素,但我不确定如何将其转换为帮助我获取上面属性的集合/列表。

List<string> desiredAttributes = new List<string>();
desiredAttributes.AddRange(new string[] { "firstName", "preferredName", "christianName", "firstInitial", "middleName" });

XDocument document = XDocument.Load(xmlStream);

IEnumerable<XElement> theResults = document.Descendants()
    .Where(el => el.Attributes().Any(att => desiredAttributes.Contains(att.Name.LocalName)));

最佳答案

您可以使用SelectMany()从每个元素返回所有所需的属性,然后将结果投影到您方便的数据结构中:

var theResults = document.Descendants()
    //select all the desired attributes
    .SelectMany(el => el.Attributes().Where(att => desiredAttributes.Contains(att.Name.LocalName)))
    //projet the result into your data structure of choice (class, array, tuple, etc.)
    .Select(att => Tuple.Create(att.Parent.Name.LocalName, att.Name.LocalName, att.Value));

foreach(var result in theResults)
{
    Console.WriteLine(result.ToString());
}

dotnetfiddle demo

输出:

(manager, firstName, Dat)
(employee, firstName, Jonathan)
(employee, preferredName, Jon)
(employee, christianName, Jane)
(employee, firstInitial, A)
(employee, middleName, J)

关于c# - Linq to XML 获取一对多元素名称和属性名称/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41918052/

相关文章:

c# - 来自字符串的 XDocument XML 模式

c# - 在 C# 中可以使用什么替代方法来避免方法返回 `object` 类型?

c# - 无法使用 Color.FromArgb 设置透明度(但 Color.Transparent 有效)

c# - 如何取消订阅 NLog 目标

c# - 使用 LinqToXml 使用过滤器选择唯一的 XElements(按属性)

c# - 我在这个 LINQ 语句中做错了什么?

c# - 如何在 linq to xml 中交换两个 XML 元素

c# - 是否可以仅在加载所有模块后才显示 shell?

c# - MS Word 加载项 : RIght click handler

c# - XDocument 对不为空的对象的空引用