2009-04-30 7 views
2

xml의 모든 정보를 배열에 저장해야합니다. 저는 항상 XML에서 첫 번째 항목 만 가져 오기 때문에 코드가 작동하지 않습니다.C# LINQ - XML ​​읽기

누구든지 해결 방법을 알고 있습니까?

  XDocument xdoc = XDocument.Load("http://www.thefaxx.de/xml/nano.xml"); 
     var items = from item in xdoc.Descendants("items") 
        select new 
        { 
         Title = item.Element("item").Element("title").Value, 
         Description = item.Element("item").Element("description").Value 
        }; 

     foreach (var item in items) 
     { 
      listView1.Items.Add(item.Title); 
     } 
+0

XML 모양은 무엇입니까? –

답변

4

방법에 대해 :

var items = from item in xdoc.Descendants("item") 
       select new 
       { 
        Title = item.Element("title").Value, 
        // *** NOTE: xml has "desc", not "description" 
        Description = item.Element("desc").Value 
       }; 

그것은이다 작은 샘플 XML없이 확인하기 어려운 -하지만 당신은 모든 <item>...</item> 요소를 반복하려는 것 같습니다 - 무엇을 위이다 않습니다. 원래 코드는 (단일?) <items>...</items> 요소를 반복하고 그 안에있는 첫 번째 <item>...</item>을 가져옵니다.


편집 후 xml; 더 효율적일 것입니다 :

var items = from item in xdoc.Root.Elements("item") 
       select new { 
        Title = item.Element("title").Value, 
        Description = item.Element("desc").Value 
       };