Create XML using class XmlTextWriter

来源:互联网 发布:阿尔德里奇数据 编辑:程序博客网 时间:2024/05/17 02:14

This is an example to create XML document using XmlTextWriter in C#.

 

The following XML is the result i want to generate.

  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 as follows,

  1. XmlTextWriter xtw = new XmlTextWriter("d://file.xml", Encoding.Default);
  2.             xtw.Formatting = Formatting.Indented;
  3.             xtw.WriteStartDocument();
  4.             xtw.WriteStartElement("Books");
  5.             // First Book
  6.             xtw.WriteStartElement("Book");
  7.             // write book attributes
  8.             xtw.WriteAttributeString("genre""Mystery");
  9.             xtw.WriteAttributeString("publicationdate""2001");
  10.             xtw.WriteAttributeString("ISBN""123456789");
  11.             // write book elements
  12.             xtw.WriteElementString("title""The Case of the Missing Cookie");
  13.             // write sub element
  14.             xtw.WriteStartElement("author");
  15.             xtw.WriteAttributeString("Country""America");
  16.             xtw.WriteElementString("name""Cookie Monster");
  17.             xtw.WriteEndElement();
  18.             xtw.WriteElementString("price""$9.99");
  19.             xtw.WriteEndElement();
  20.             xtw.WriteEndElement();
  21.             xtw.WriteEndDocument();
  22.             // close writer
  23.             xtw.Close();
原创粉丝点击