当前位置: 移动技术网 > IT编程>开发语言>c# > C# Linq读取XML文件的实例

C# Linq读取XML文件的实例

2019年07月18日  | 移动技术网IT编程  | 我要评论
1、示例xml文件:demo.xml 复制代码 代码如下:<?xml version="1.0" encoding="utf-8" ?><note>

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网