zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#Linq读取XML文件的实例

c#实例文件XML 读取 LinQ
2023-06-13 09:14:54 时间

1、示例XML文件:Demo.xml

复制代码代码如下:


<?xmlversion="1.0"encoding="utf-8"?>
<note>
 <conf>
   <to>infozero</to>
   <from>lerroy</from>
   <heading>测试信息</heading>
   <body>第一条测试信息</body>
   <titlename="我的第一条消息">frommyself</title>
 </conf>
 <conf>
   <to>infozero@163.com</to>
   <from>text</from>
   <heading>时刻提醒我</heading>
   <body>这是一条测试信息!</body>
   <titlename="我的第二条消息">fromothers</title>
 </conf>
</note>

2、在程序中引用以下命名空间

复制代码代码如下:


usingSystem;
usingSystem.Linq;
usingSystem.Xml.Linq;

3、读取代码如下:

复制代码代码如下:
classProgram
   {
       staticvoidMain(string[]args)
       {
           XDocumentdoc=XDocument.Load("demo.xml");
           vartext=fromtindoc.Descendants("conf")                   //定位到节点
                      .Where(w=>w.Element("to").Value.Contains("@"))  //若要筛选就用上这个语句
                      selectnew
                      {
                          to=t.Element("to").Value,
                          froms=t.Element("from").Value,
                          head=t.Element("heading").Value,
                          body=t.Element("body").Value,
                          title=t.Element("title").Attribute("name").Value  //注意此处用到attribute
                      };
           foreach(varaintext)
           {
               Console.WriteLine(a.to);
               Console.WriteLine(a.froms);
               Console.WriteLine(a.head);
               Console.WriteLine(a.body);
               Console.WriteLine(a.title);
           }
           Console.ReadKey();
       }
   }