The result XML document is as follows:
- <?xml version="1.0" encoding="GB2312"?>
- <Books>
- <Book genre="Mystery" publicationdate="2001" ISBN="123456789">
- <title>The Case of the Missing Cookie</title>
- <author Country="America">
- <Name>Cookie Monster</Name>
- </author>
- <Price>$9.99</Price>
- </Book>
- </Books>
The C# code is:
- XmlDocument xmlDoc = new XmlDocument();
- // Create XML declaration
- XmlDeclaration xdl = xmlDoc.CreateXmlDeclaration("1.0", "GB2312", null);
- xmlDoc.AppendChild(xdl);
- // Create root node "Books"
- XmlElement books = xmlDoc.CreateElement("Books");
- // Create child node book infomation
- XmlElement book1 = xmlDoc.CreateElement("Book");
- // set node attributes
- book1.SetAttribute("genre", "Mystery");
- book1.SetAttribute("publicationdate", "2001");
- book1.SetAttribute("ISBN", "123456789");
- // create sub elements for book
- XmlElement title = xmlDoc.CreateElement("title");
- title.InnerText = "The Case of the Missing Cookie";
- book1.AppendChild(title);
- XmlElement author = xmlDoc.CreateElement("author");
- author.SetAttribute("Country", "America");
- book1.AppendChild(author);
- XmlElement authorName = xmlDoc.CreateElement("Name");
- authorName.InnerText = "Cookie Monster";
- author.AppendChild(authorName);
- XmlElement price = xmlDoc.CreateElement("Price");
- price.InnerText = "$9.99";
- book1.AppendChild(price);
- // add book information to books which is root element of the document
- books.AppendChild(book1);
- // add root node to document
- xmlDoc.AppendChild(books);
- // save the xml document to file system
- xmlDoc.Save("d://file1.xml");