LINQ to read XML

前端 未结 5 1927
逝去的感伤
逝去的感伤 2020-11-22 00:47

I got this XML file:


    
        
        
             


        
5条回答
  •  感情败类
    2020-11-22 01:33

    Try this.

    using System.Xml.Linq;
    
    void Main()
    {
        StringBuilder result = new StringBuilder();
    
        //Load xml
        XDocument xdoc = XDocument.Load("data.xml");
    
        //Run query
        var lv1s = from lv1 in xdoc.Descendants("level1")
                   select new { 
                       Header = lv1.Attribute("name").Value,
                       Children = lv1.Descendants("level2")
                   };
    
        //Loop through results
        foreach (var lv1 in lv1s){
                result.AppendLine(lv1.Header);
                foreach(var lv2 in lv1.Children)
                     result.AppendLine("     " + lv2.Attribute("name").Value);
        }
    
        Console.WriteLine(result);
    }
    

提交回复
热议问题