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

时间:2017-01-29 05:51:26

标签: 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>

我想返回所有element-name / attribute-name / attribute-value组合的集合/列表,其中属性名称在{“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,下面是返回正确的元素,但我不确定如何将其转换为一个集合/列表,帮助我获得上面的属性。

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)));

1 个答案:

答案 0 :(得分:1)

您可以使用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)