LINQ to XML

创建XML文档

LINQ to XML

 

 1.使用XMLDocument的方式

LINQ to XML
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));
            XmlElement newbook = doc.CreateElement("book");
            newbook.SetAttribute("genre", "Mystery");
            newbook.SetAttribute("publicationdate", "2001");
            newbook.SetAttribute("ISBN", "123345525");

            XmlElement newTitle = doc.CreateElement("title");
            newTitle.InnerText = "The Case of The missing cookie";
            newbook.AppendChild(newTitle);

            XmlElement newAuthor = doc.CreateElement("Author");
            newAuthor.InnerText = "James Lorain";
            newbook.AppendChild(newAuthor);
            if (doc.DocumentElement == null)
                doc.AppendChild(newbook);
            XmlTextWriter tr = new XmlTextWriter("newbook.xml", Encoding.UTF8);
            tr.Formatting = Formatting.Indented;
            doc.WriteContentTo(tr);
            tr.Close();
View Code

2.使用XDocument的方式

 

            XDocument xdoc = new XDocument();
            XElement root = new XElement("Book");
            xdoc.Add(root);

            XAttribute genre = new XAttribute("genre", "Mystery");
            XAttribute date = new XAttribute("publicationdate", "2001");
            XAttribute isbn = new XAttribute("ISBN", "123345525");
            root.Add(genre, date, isbn);

            XElement title = new XElement("title");
            title.Value = "The Case of The missing cookie";

            XElement author = new XElement("Author", "James Lorain");
            root.Add(title, author);

            xdoc.Save("xdoc.xml");

 

上一篇:leetcoe系列之删除数组中的重复值


下一篇:UIToolkit编辑器练习(一)