请问如何应用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个回答

    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 太感谢了 真是高手
3 年多之前 回复
             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属性相同,有没有更合适的写法,

    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

立即提问
相关内容推荐