Create XML using class XmlDocument

来源:互联网 发布:数据结构算法2.1 编辑:程序博客网 时间:2024/05/08 15:21

 The result XML document is as follows:

  1. <?xml version="1.0" encoding="GB2312"?>
  2. <Books>
  3.   <Book genre="Mystery" publicationdate="2001" ISBN="123456789">
  4.     <title>The Case of the Missing Cookie</title>
  5.     <author Country="America">
  6.       <Name>Cookie Monster</Name>
  7.     </author>
  8.     <Price>$9.99</Price>
  9.   </Book>
  10. </Books>

The C# code is:

  1. XmlDocument xmlDoc = new XmlDocument();
  2.             // Create XML declaration
  3.             XmlDeclaration xdl = xmlDoc.CreateXmlDeclaration("1.0""GB2312"null);
  4.             xmlDoc.AppendChild(xdl);
  5.             // Create root node "Books"
  6.             XmlElement books = xmlDoc.CreateElement("Books");
  7.             // Create child node book infomation
  8.             XmlElement book1 = xmlDoc.CreateElement("Book");
  9.             // set node attributes
  10.             book1.SetAttribute("genre""Mystery");
  11.             book1.SetAttribute("publicationdate""2001");
  12.             book1.SetAttribute("ISBN""123456789");
  13.             // create sub elements for book
  14.             XmlElement title = xmlDoc.CreateElement("title");
  15.             title.InnerText = "The Case of the Missing Cookie";
  16.             book1.AppendChild(title);
  17.             XmlElement author = xmlDoc.CreateElement("author");
  18.             author.SetAttribute("Country""America");
  19.             book1.AppendChild(author);
  20.             XmlElement authorName = xmlDoc.CreateElement("Name");
  21.             authorName.InnerText = "Cookie Monster";
  22.             author.AppendChild(authorName);
  23.             XmlElement price = xmlDoc.CreateElement("Price");
  24.             price.InnerText = "$9.99";
  25.             book1.AppendChild(price);
  26.             // add book information to books which is root element of the document
  27.             books.AppendChild(book1);
  28.             // add root node to document
  29.             xmlDoc.AppendChild(books);
  30.             // save the xml document to file system
  31.             xmlDoc.Save("d://file1.xml");
原创粉丝点击