2011-04-26 49 views

回答

0

這將打印出每個塊和所有的字段:

var tree = XElement.Parse(text); 
foreach(var farm in tree.Descendants("farm")) 
{ 
    Console.WriteLine(farm.Attribute("Name").Value); 
    // print the blocks and their fields 
    foreach(var block in farm.Descendants("block")) 
    { 
     Console.WriteLine("\t{0}", block.Attribute("Name").Value); 
     foreach(var field in block.Descendants("field")) 
      Console.WriteLine("\t\t{0}", field.Attribute("Name").Value); 
    } 
    // print out the remaining fields that don't belong to a block 
    foreach(var field in farm.Descendants("field")) 
    { 
     Console.WriteLine("\t{0}", field.Attribute("Name").Value); 
    } 
} 

像這樣:

Farm A 
    Field 1 
Farm B 
    Block North 
    Field 11 
    Field 12 
    Block South 
    Field 25 
    Field 26 
    Field 27 
    Field 28 
    Field 11 
    Field 12 
    Field 25 
    Field 26 
    Field 27 
    Field 28 
+0

感謝u.but其實我的XML文件看起來像this.how我可以顯示使用LINQ的所有節點<部門名稱= 「部門主」 ID = 「1」> <場。名稱=「Farm A」> <字段名稱= 「字段26」/> <字段名稱= 「字段27」/> <字段名稱= 「字段28」/> mihirprasad 2011-04-27 06:31:23

+0

@mihirprasad:這是更好? – alex 2011-04-27 06:50:32

相關問題