所有代码都在同一个类中,含有对象

XmlDocument doc = new XmlDocument();

新建XML,并且写入内容

        private void button4_Click(object sender, EventArgs e)
        {
            
            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();
        }

创建的xml文件内容为

C# XML操作之一:使用XmlDocument来读写

 

往已有XML文件中添加内容

原有books.xml内容如下

 

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--  Copyright w3school.com.cn -->
<!-- W3School.com.cn bookstore example -->
<bookstore>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
</bookstore>
View Code

相关文章:

  • 2022-12-23
  • 2021-06-09
  • 2022-12-23
  • 2022-12-23
  • 2021-09-28
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-28
  • 2022-12-23
相关资源
相似解决方案