C# Linq讀取XML文件的實例
更新時間:2013年05月21日 09:19:16 作者:
C# Linq讀取XML文件的實例,需要的朋友可以參考一下
1、示例XML文件:Demo.xml
復(fù)制代碼 代碼如下:
<?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、在程序中引用以下命名空間
復(fù)制代碼 代碼如下:
using System;
using System.Linq;
using System.Xml.Linq;
3、讀取代碼如下:
復(fù)制代碼 代碼如下:
class Program
{
static void Main(string[] args)
{
XDocument doc = XDocument.Load("demo.xml");
var text = from t in doc.Descendants("conf") //定位到節(jié)點
.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();
}
}
相關(guān)文章
.NET中的靜態(tài)與非靜態(tài)的區(qū)別分析
.NET中的靜態(tài)與非靜態(tài)的區(qū)別分析,需要的朋友可以參考一下2013-03-03
WPF實現(xiàn)在控件上顯示Loading等待動畫的方法詳解
這篇文章主要介紹了WPF 如何在控件上顯示 Loading 等待動畫,文中的示例代碼講解詳細,對我們學(xué)習或工作有一定幫助,需要的可以參考一下2023-03-03
DevExpress實現(xiàn)GridView當無數(shù)據(jù)行時提示消息
這篇文章主要介紹了DevExpress實現(xiàn)GridView當無數(shù)據(jù)行時提示消息,需要的朋友可以參考下2014-08-08

