我的 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());
}
输出:
(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/