创建XMl
public ActionResult Contact()
{
//使用XDocument创建xml
System.Xml.Linq.XDocument xdoc = new XDocument();
XDeclaration xdec = new XDeclaration("1.0", "utf-8", "yes");
xdoc.Declaration = xdec;
//添加根节点
XElement rootEle = new XElement("school");
xdoc.Add(rootEle);
//给根节点添加子节点
XElement classEle = new XElement("class");
XAttribute attrClass = new XAttribute("No", 1);
classEle.Add(attrClass);
rootEle.Add(classEle);
//添加子节点下的元素
XElement stuEle = new XElement("student");
XAttribute atrStu = new XAttribute("sid", "20180101");
stuEle.Add(atrStu);
classEle.Add(stuEle);
//保存文件
xdoc.Save("d:\\TestB.xml");
Console.WriteLine("创建xml文件ok");
Console.ReadKey();
return View();
}
追加XML 加点
string patch = "D:\\123.xml";
XElement rootEle = xd1.Root;
//给根节点添加子节点
XElement classEle = new XElement("Person");
XAttribute attrClass = new XAttribute("phone", "222rr");
XAttribute AuthCodeCount = new XAttribute("AuthCodeCount", 10);
XAttribute AuthCodeTime = new XAttribute("AuthCodeTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
classEle.Add(attrClass);
classEle.Add(AuthCodeCount);
classEle.Add(AuthCodeTime);
rootEle.Add(classEle);
xd1.Save(patch);
修改XMl信息
SetAttributeValue 修改属性与新增实质是同一个方法 有相同属性信息时修改,没有则新增
XDocument xDoc = XDocument.Load(patch);
XElement element = xDoc.Element("config").Element("Person");
element.SetAttributeValue("BookName", "Test");
xDoc.Save(patch);