您的位置:首页 > 其它

Create XML using class XmlTextWriter

2008-12-11 11:30 453 查看
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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: