一、创建的第一种方式
//1、创建一个XML文档
XmlDocument doc = new XmlDocument();
//2、创建第一行描述信息
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
//3、将创建的第一行描述信息添加到文档中
doc.AppendChild(dec);
//4、给文档添加根节点
XmlElement Books = doc.CreateElement("Books");
doc.AppendChild(Books);
XmlElement Book = doc.CreateElement("Book");
Books.AppendChild(Book);
XmlElement name = doc.CreateElement("name");
name.InnerText = "水浒传";
Book.AppendChild(name);
XmlElement author = doc.CreateElement("author");
author.InnerText = "匿名";
author.SetAttribute("name", "wjl");
author.SetAttribute("count", "30");
Book.AppendChild(author);
doc.Save("Book.xml");
Console.WriteLine("保存成功!");
Console.ReadKey();
创建结果如下:
二、创建的第二种方式
class Program
{
static void Main(string[] args)
{
List<Student> list = new List<Student>();
list.Add(new Student(1, "wjl1", 22, "男"));
list.Add(new Student(2, "wjl2", 21, "男"));
list.Add(new Student(3, "wjl3", 22, "男"));
list.Add(new Student(4, "wjl4", 24, "男"));
XmlDocument xmldoc = new XmlDocument();
XmlDeclaration xmldec = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);
xmldoc.AppendChild(xmldec);
XmlElement person = xmldoc.CreateElement("Person");
xmldoc.AppendChild(person);
for (int i= 0;i < list.Count; i++)
{
XmlElement stu = xmldoc.CreateElement("student");
stu.SetAttribute("ID", list[i].Id.ToString());
person.AppendChild(stu);
XmlElement name = xmldoc.CreateElement("name");
XmlElement age = xmldoc.CreateElement("age");
name.InnerText = list[i].Name;
age.InnerText = list[i].Age.ToString();
stu.AppendChild(name);
stu.AppendChild(age);
}
xmldoc.Save("Student.xml");
Console.WriteLine("Student.xml");
Console.ReadKey();
}
}
class Student {
int id;
string name;
int age;
string sex;
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string Sex
{
get
{
return sex;
}
set
{
sex = value;
}
}
public Student(int id, string name, int age, string sex)
{
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
public Student()
{
}
}
创建结果如下:
三、对XML文件的添加
XmlDocument doc = new XmlDocument();
//首先判断文件是否存在,如果存在则追加否则在创建一个
if (File.Exists("Student.xml"))
{
//加载
doc.Load("Student.xml");
//获取根节点,给根节点添加子节点
XmlElement person = doc.DocumentElement;
XmlElement student = doc.CreateElement("student");
student.SetAttribute("ID", "1");
person.AppendChild(student);
XmlElement name = doc.CreateElement("name");
XmlElement age = doc.CreateElement("age");
name.InnerText = "zjs";
age.InnerText = "41";
student.AppendChild(name);
student.AppendChild(age);
}
else {
}
doc.Save("Student.xml");
Console.WriteLine("Student.xml 保存成功");
四、对XML文档的