Linq To Xml 创建修改xml文档

时间:2022-10-14 05:45:00
 static void Main(string[] args)
        {
            //创建xml文件
            string path = @"E:\LinqToXmlTest.xml";
            XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
            new XElement("Root",
                new XElement("AccessCount",
                    new XAttribute("ClientId", 123),
                    new XAttribute("DateTime", DateTime.Now.ToString()))
                ));
            xdoc.Save(path);



            //读取xml文档
            XElement root = XElement.Load(@"E:\LinqToXmlTest.xml");

            //修改xml文档
            var clientinfo = from h in root.Descendants("AccessCount")
                             where h.Attribute("ClientId").Value == "123"
                             select h;
            var r = clientinfo.Single<XElement>();
            r.ReplaceWith(new XElement("AccessCount",
                 new XAttribute("ClientId", 123456789),
                   new XAttribute("DateTime", DateTime.Now.ToString())));


            //最后保存文件
            root.Save(@"E:\LinqToXmlTest.xml");
        }