This is an example to create XML document using XmlTextWriter in C#.
The following XML is the result i want to generate.
- <?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 as follows,
- XmlTextWriter xtw = new XmlTextWriter("d://file.xml", Encoding.Default);
- xtw.Formatting = Formatting.Indented;
- xtw.WriteStartDocument();
- xtw.WriteStartElement("Books");
- // First Book
- xtw.WriteStartElement("Book");
- // write book attributes
- xtw.WriteAttributeString("genre", "Mystery");
- xtw.WriteAttributeString("publicationdate", "2001");
- xtw.WriteAttributeString("ISBN", "123456789");
- // write book elements
- xtw.WriteElementString("title", "The Case of the Missing Cookie");
- // write sub element
- xtw.WriteStartElement("author");
- xtw.WriteAttributeString("Country", "America");
- xtw.WriteElementString("name", "Cookie Monster");
- xtw.WriteEndElement();
- xtw.WriteElementString("price", "$9.99");
- xtw.WriteEndElement();
- xtw.WriteEndElement();
- xtw.WriteEndDocument();
- // close writer
- xtw.Close();