2017-01-29 16 views
1

私はこのようなXMLを持っている:XMLにLINQのは、1対多の要素名を取得し、属性に名前/値

<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"、 "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

あなたは、各要素から必要なすべての属性を返すために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) 
+0

「親」を使ってツリーを見直す...私はあまりにも忙しすぎて、それについて逆に考えていませんでした。ありがとう。 – ThunderFrame

関連する問題