首页 > 代码库 > linq 读取xml文件

linq 读取xml文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace linq_to_xml
{
    internal class Program
    {
        private static void Main(string[] args)
        {
          

            #region

          XDocument xml = XDocument.Load(@"C:\Users\yunxia\Desktop\linq to xml\linq to xml\ServerList.xml"); //使用XDocument的构造函数可以构造一个Xml文档对象
          var query = from x in xml.Descendants("ServerList").Elements("object")
                      //使用XElement对象可以构造一个xml节点元素
                      select new
                      {
                          //使用XAttribute构造函数可以构造元素的属性
                          Server_id = x.Attribute
                              ("Server_id").Value,
                          IP_Address = x.Attribute
                               ("IP_Address").Value,
                          Server_Name = x.Attribute
                              ("Server_Name").Value,
                          New_Server = x.Attribute
                             ("New_Server").Value
                      };
        foreach(var q in query)
         {
             Console.WriteLine("IP_Address:{0}\tServer_Id:{1}\tServerName:{2}\tNew_Server:{3}",q.IP_Address, q.Server_id,q.Server_Name,q.New_Server);
         }
            /* 

            这是我要读的ServerList.xml文件
           <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <!-- Server_id="0"(推荐服务器)-->
<!-- New_Server=0(维护)New_Server=1(通畅)New_Server=2(正常)New_Server=3(繁忙)-->
<ServerList>
  <object Server_id="0" IP_Address="http://ws.poqop.com:8765" Server_Name="测试一服" New_Server="1"/>
  <object Server_id="1" IP_Address="http://ws.poqop.com:8765" Server_Name="测试一服" New_Server="1"/>
  <object Server_id="2" IP_Address="http://ws.poqop.com:8765" Server_Name="测试二服" New_Server="1"/>
  <object Server_id="3" IP_Address="http://localhost:8205/" Server_Name="for fatlin" New_Server="2"/>
</ServerList>
            */
        }

            #endregion


        }


    }

 

总结:

x.Element与x.Attribute要弄清楚,刚开始我就是弄混了,一直没调试出来Element是元素节点,Element才是属性。而我已经把object设为节点了,所以很明显它在节点里面,才是属性。

使用XElement对象可以构造一个xml节点元素。使用XAttribute构造函数可以构造元素的属性。