日期:2014-05-20  浏览次数:21018 次

用LINQ遍历 XML子节点
<?xml version="1.0" encoding="utf-8" ?> 
 <zyxml>
<server_s>
 <server>
  <id>10</id> 
  <name>张三</name> 
  <server_id>1</server_id> 
  </server>
  <server>
  <id>10</id> 
  <name>李四</name> 
  <server_id>2</server_id> 
  </server>
  <server>
  <id>10</id> 
  <name>王五</name> 
  <server_id>3</server_id> 
  </server>
<server_s>

用linq怎么遍历出全部的name和server_id呢?


------解决方案--------------------
C# code

void Main()
{
    XDocument xml=XDocument.Load("c:\\test.xml");
    var query=from x in xml.Descendants("server") 
              select new{name=x.Element("name").Value,server_id=x.Element("server_id").Value};
    foreach(var q in query)
    {
      Console.WriteLine("Name:{0}\tServerId:{1}",q.name,q.server_id);
    }
      /*
        Name:张三    ServerId:1
        Name:李四    ServerId:2
        Name:王五    ServerId:3

      */
}