2016-10-08 16 views
2

Linq To XMLを使用してXMLファイルを読み込もうとしていますが、その方法を理解できないようです。C#Linq to XMLで属性を持つ複数のタグを読み取る

私は、このXMLファイルを持っている:

<?xml version="1.0" encoding="utf-8" ?> 
<Thing> 
    <Objects> 
     <MyTag name="" num="2"> 
      <Date month="May" day="2" year="2006" /> 
     </MyTag> 

     <MyTag name="" num="4"> 
      <Date month="May" day="22" year="2012" /> 
     </MyTag> 

     <MyTag name="" num="2"> 
      <Date month="May" day="11" year="2034" /> 
     </MyTag> 
    </Objects> 
</Thing> 

を私はこのクエリを開始しました:

// Load the xml 
XDocument document = XDocument.Load(XML_PATH); 

var query = from thing in document.Root.Descendants("Objects") 
      select new 
      { 
       TagName = thing.Attribute("name").Value.ToString(), 
       TagNum = thing.Attribute("num").Value.ToString(), 

       // What do I write here to get the Date tag and attributes? 
      }; 

にはどうすればいいDateタグや属性になるだろうか?次のノードを取得する方法がわかりません。

私はこのようなforeachループ内TagNameTagNumを印刷してみました:

foreach(string value in query) 
{ 
    Console.WriteLine(value.TagName + " " + value.TagNum); 
} 

しかし、私はこのような

CS0030 Cannot convert type '<anonymous type: string TagName, string TagNum>' to 'string' 
+1

使用 'foreachの(クエリ内のvar値)' – Fabio

答えて

2

はちょうど子供を取得するために.Element()を使用して、日付を取得するには、次のqueryコレクションがnew{}によって返された匿名型の場合、あなたが文字列を求めているので、

from thing in document.Root.Descendants("Objects") 
let date = thing.Element("Date") 
select new 
{ 
    TagName = (string)thing.Attribute("name"), 
    TagNum = (string)thing.Attribute("num"), 

    DateMonth = (string)date?.Attribute("month"), 
    DateDay = (string)date?.Attribute("day"), 
    DateYear = (string)date?.Attribute("year"), 
}; 

あなたforeachステートメントがコンパイルされていません。

foreach(var value in query) 
{ 
    Console.WriteLine(value.TagName + " " + value.TagNum); 
} 
+1

説明をありがとう。これからたくさん学んだ。 – cress

1

変更して、varタイプの代わりに言って、エラーを取得しています

foreach (var value in query) 
{ 
    Console.WriteLine(value.TagName + " " + value.TagNum); 
} 
+1

をありがとう:あなたはvarの代わりstringを使用したいと思います。クエリからのすべてが文字列として来たと思った。 – cress

1

使用Element("elementName")方法

var query = 
    document.Root 
      .Descendants("Objects") 
      .Select(obj => new 
      { 
       TagName = thing.Attribute("name").Value, 
       TagNum = thing.Attribute("num").Value, 
       Year = thing.Element("Date").Attribute("year").Value, 
       Month = thing.Element("Date").Attribute("month").Value, 
       Day = thing.Element("Date").Attribute("day").Value 
      }; 
+1

助けてくれてありがとう! – cress

関連する問題