加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C# Linq读取XML文件的实例

发布时间:2020-12-15 04:16:16 所属栏目:百科 来源:网络整理
导读:1、示例XML文件:Demo.xml 复制代码 代码如下: ?xml version="1.0" encoding="utf-8" ? note conf toinfozero/to fromlerroy/from heading测试信息/heading body第一条测试信息/body title name="我的第一条消息"from myself/title /conf conf toinfozero@16

1、示例XML文件:Demo.xml

复制代码 代码如下:

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

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

复制代码 代码如下:

using System;
using System.Linq;
using System.Xml.Linq;

3、读取代码如下:

复制代码 代码如下:

class Program
    {
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load("demo.xml");
            var text = from t in doc.Descendants("conf")                    //定位到节点
                       .Where(w => w.Element("to").Value.Contains('@'))   //若要筛选就用上这个语句
                       select new
                       {
                           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 (var a in text)
            {
                Console.WriteLine(a.to);
                Console.WriteLine(a.froms);
                Console.WriteLine(a.head);
                Console.WriteLine(a.body);
                Console.WriteLine(a.title);
            }
            Console.ReadKey();
        }
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读