我的上一篇文章描述了用普通方法实现对xml文件的基本操作,感谢各位园友给我提的每一个建议,大家主要在说:用Linq去实现对xml的操作更加 方便简洁,于是乎我就现学习了一下Linq to xml,由于是刚刚接触Linq,理解肯定不会很深,所以请各位园友不吝赐教,有建议尽管说,在此先谢过大家啦~
- <Users>
- <User ID="111111">
<name>EricSun</name>
<password>123456</password>
<description>Hello I'm from Dalian</description>
</User>
- <User ID="222222">
<name>Ray</name>
<password>654321</password>
<description>Hello I'm from Jilin</description>
</User>
</Users>
用我的上篇文章也能够很容的实现,不过下面我要用Linq to xml的方式实现生成这个xml文件,请看下面代码: 【注:由于使用了Linq to xml的方式,所以要引入命名空间System.Xml.Linq】,通过运行上面这段代码,就可以创建我们预想的xml文件结构,并且可以看出用 Linq这种方式,在代码中就可以很清楚明了知道我们创建xml文件的结构(如:构造函数的参数所示)
用我的上篇文章也能够很容的实现,不过下面我要用Linq to xml的方式实现生成这个xml文件,请看下面代码:
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Xml.Linq;
6
7 namespace OperateXmlLinq
8 {
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 //xml文件存储路径
14 string myXmlPath = "E:\\MyUsers.xml";
15 //创建xml文件
16 GenerateXmlFile(myXmlPath);
17 }
18
19 private static void GenerateXmlFile(string xmlPath)
20 {
21 try
22 {
23 //定义一个XDocument结构
24 XDocument myXDoc = new XDocument(
25 new XElement("Users",
26 new XElement("User", new XAttribute("ID", "111111"),
27 new XElement("name", "EricSun"),
28 new XElement("password", "123456"),
29 new XElement("description", "Hello I'm from Dalian")
30 ),
31 new XElement("User", new XAttribute("ID", "222222"),
32 new XElement("name", "Ray"),
33 new XElement("password", "654321"),
34 new XElement("description", "Hello I'm from Jilin")
35 )
36 )
37 );
38 //保存此结构(即:我们预期的xml文件)
39 myXDoc.Save(xmlPath);
40 }
41 catch (Exception ex)
42 {
43 Console.WriteLine(ex.ToString());
44 }
45 }
46 }