1.创建
1.创建一个xml文件 XDocument xDoc = new XDocument(new XDeclaration("1.0","utf-8","yes")); 2.创建子节点 XElement xele = new XElement(new XElement("students",//最外层父节点 new XElement("student",//父节点,节点student new XElement("姓名","张三"),//student节点下,创建姓名节点 new XElement("年龄","18"),//依次...都是student的子节点 new XElement("班级","土匪班") ),new XElement("student",new XElement("姓名","李四"),new XElement("年龄",19),new XElement("班级","悍匪班") ) )); 3.将子节点添加到文档,保存文件。 xDoc.Add(xele); xDoc.Save("Student-1.xml");
2.读取
//加载xml文件 XDocument xDoc = XDocument.Load("Student-1.xml"); var temp = from doc in xDoc.Descendants("student") //where doc.Name == "姓名" select doc; foreach (var item in temp) { Console.WriteLine(item); }
3.追加
XDocument xDoc = XDocument.Load("Student-1.xml");
xDoc.Root.Add(new XElement("student","王五"),"22"),"共产党")
)
);
xDoc.Save("Student-1.xml");
foreach (var item in xDoc.Descendants("student"))
{
Console.WriteLine(item);
}
4.删除
XDocument xDoc = XDocument.Load("Student-1.xml");
var temp = from u in xDoc.Descendants("姓名")
where u.Value == "王五"
select u.Parent;
temp.ToList().Remove();
xDoc.Save("Student-1.xml");
foreach (var item in xDoc.Descendants("student"))
{
Console.WriteLine(item);
}