Linq to XML 获取一对多元素名称和属性 name/value

Linq to XML to get one-to-many Element Name and Attribute name/value

我有 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>

我想要 return 所有 element-name/attribute-name/attribute-value 组合的 collection/list,其中属性名称位于 { "firstName"、"preferredName"、"christianName", "firstInitial", "middleName" }

鉴于上述 XML,我有一个如下所示的列表:

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

我在下面有一些 LINQ,即 returning 正确的元素,但我不确定如何将其转换为 collection/list 以帮助我获得上述属性.

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() 到 return 每个元素的所有所需属性,然后将结果投影到您方便的数据结构中:

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)