C# Linq读取XML文件

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();
        }
    }

 

转载于:https://www.cnblogs.com/shawnzhou/archive/2013/05/20/3089814.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值