C#用XDocument操作XML
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace XML_Practice
{
//创建Person类
public class Person
{
private string _name;
private int _age;
private char _gender;
private int _salary;
public string Name { get => _name; set => _name = value; }
public int Age { get => _age; set => _age = value; }
public char Gender { get => _gender; set => _gender = value; }
public int Salary { get => _salary; set => _salary = value; }
//带参数的构造器
public Person(string na,int ag,char ge,int sa)
{
this._name = na;
this._age = ag;
this._gender = ge;
this._salary = sa;
}
//无参数的构造器
public Person()
{
}
}
class Program
{
static void Main(string[] args)
{
List<Person> persons = new List<Person>() { new Person("李刚",23,'男',10000),
new Person("张三",45,'女',3400),
new Person("李四",67,'男',4500),
new Person("王五",43,'男',9800)};
#region xDoc来操作xml文件
XDocument xdoc = new XDocument();
XDeclaration xdec = new XDeclaration("1.0", "utf-8", "yes");
xdoc.Declaration = xdec;
//根节点
XElement xElem = new XElement("List");
for (int i=0;i<persons.Count;i++)
{
//创建一个person元素
XElement xpersonElement = new XElement("Person");
//把person挂在根节点上
xElem.Add(xpersonElement);
//创建name元素
XElement nameElement = new XElement("name",persons[i].Name);
xpersonElement.Add(nameElement);
//创建age元素
XElement ageElement = new XElement("age", persons[i].Age.ToString());
xpersonElement.Add(ageElement);
//创建gender元素
XElement genderElement = new XElement("gender", persons[i].Gender.ToString());
genderElement.Add(genderElement);
//创建salary元素
XElement salaryElement = new XElement("salary", persons[i].Salary.ToString());
xpersonElement.Add(salaryElement);
}
//将根节点挂在xdoc上
xdoc.Add(xElem);
xdoc.Save("person.xml");
#endregion
Console.WriteLine("写入成功!");
Console.ReadKey();
}
}
}
创建的效果如下:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<List>
<Person>
<name>李刚</name>
<age>23</age>
<salary>10000</salary>
</Person>
<Person>
<name>张三</name>
<age>45</age>
<salary>3400</salary>
</Person>
<Person>
<name>李四</name>
<age>67</age>
<salary>4500</salary>
</Person>
<Person>
<name>王五</name>
<age>43</age>
<salary>9800</salary>
</Person>
</List>