作者:新维斯教育逄博 | 来源:互联网 | 2021-09-05 01:07
1、示例XML文件:Demo.xml
代码如下:
infozero
lerroy
测试信息
第一条测试信息
infozero@163.com
text
时刻提醒我
这是一条测试信息!
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();
}
}