u011387568
神采飞扬0
2017-07-10 06:11
采纳率: 66.7%
浏览 754
已采纳

请问如何应用linq读取xml

 <School>
<Text1>
  <A Value="1"/>
  <B Value="2"/>
  <C Value="1"/>
  <D Value="16"/>
  <E Value="P1,P2,P3"/>
</Text1>
<Text2>
  <A Value="2"/>
  <B Value="2"/>
  <C Value="1"/>
  <D Value="25"/>
  <E Value="P7,P8,P9"/>
</Text2>

</School>


请问怎样才能显示:Text1:1,2,1,16,P1,P2,P3;Text2:2,2,1,25,P7,P8,P9…

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • q107770540
    兔子党-督察 2017-07-18 22:49
    已采纳
        XDocument addList = XDocument.Load(@"c:\R.xml");
        var text = addList.Descendants("School").SelectMany(x=>x.Elements());
    
        foreach(var node in text)
        {
          Console.WriteLine( node.Name + "," +  string.Join("," , node.Elements().Select(el=>el.Attribute("Value").Value).ToArray())); 
        }
    
    点赞 评论
  • u011387568
    神采飞扬0 2017-07-10 06:23
                 XDocument addList = XDocument.Load(@"R.xml");
                                        var text = from v in addList.Descendants("Text1")
                           select new
                           {
                               a = v.Element("A").Attribute("Value").Value,
                               b = v.Element("B").Attribute("Value").Value,
                               c = v.Element("C").Attribute("Value").Value,
                               d = v.Element("D").Attribute("Value").Value,
                               e = v.Element("E").Attribute("Value").Value,
                                                     };
                foreach (var r in text)
                {
                    Console.WriteLine(r.a);
                    Console.WriteLine(r.b);
                    Console.WriteLine(r.c);
                    Console.WriteLine(r.d);
                    Console.WriteLine(r.e);
                }
                            Console.ReadKey();
    

    节点Text1与节点Text2属性相同,有没有更合适的写法,

    点赞 评论
  • q107770540
    兔子党-督察 2017-07-18 22:47
        XDocument addList = XDocument.Load(@"c:\R.xml");
        var text = from v in addList.Descendants("School") 
                   from x in v.Elements()
                   select x;
    
        foreach(var node in text)
        {
          Console.WriteLine( node.Name + "," +  string.Join("," , node.Elements().Select(el=>el.Attribute("Value").Value).ToArray())); 
        }
    

    Text1,1,2,1,16,P1,P2,P3
    Text2,2,2,1,25,P7,P8,P9

    点赞 评论

相关推荐