创建一个简单的XML文件并生成
XElement users = new XElement("users",
new XElement("user",
new XElement("UserID", 1),
new XElement("UserName", "lemon"),
new XElement("Password", "12345")
),
new XElement("user",
new XElement("UserID", 2),
new XElement("UserName", "jerry"),
new XElement("Password", "54321")
)
);
string path = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, @"static\users.xml");
users.Save(path);
Console.WriteLine("创建成功");
Console.WriteLine(path);
修改xml文件的内容
string path = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, @"static\users.xml");
XElement loadUsers = XElement.Load(path);
loadUsers.Add(new XElement("user2", new XElement("UserID", 3), new XElement("UserName", "free"), new XElement("Password", "112233")));
loadUsers.Save(path);
Console.WriteLine("修改成功");
删除XML内的内容 remove
string path = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, @"static\users.xml");
XElement users = XElement.Load(path);
users.Element("user2").Remove();
users.Save(path);
修改节点内的内容
string path = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, @"static\users.xml");
XElement users = XElement.Load(path);
var user = users.Element("user");
user.SetElementValue("Password", "11111");
users.Save(path);
Console.WriteLine("修改成功");