The xmltextwriter class can write XML into a stream, file, or textwriter object.
Simple Example:
Private Void Button2_click ( Object Sender, system. eventargs E)
{
String Filename = "booknew. xml ";
Xmltextwriter Tw = new xmltextwriter (filename, Null );
Tw. Formatting = formatting. indented;
Tw. writestartdocument ();
Tw. writestartelement ("book ");
Tw. writeattributestring ("genre", "mystery ");
Tw. writeattributestring ("publicationdate", "2001 ");
Tw. writeattributestring ("ISBN", "123456789 ");
Tw. writeelementstring ("title", "case of the missing cookie ");
Tw. writestartelement ("author ");
Tw. writeelementstring ("name", "Cookie Monster ");
Tw. writeendelement ();
Tw. writeelementstring ("price", "9.99 ");
Tw. writeendelement ();
Tw. writeenddocument ();
Tw. Flush ();
Tw. Close ();
}
CodeThe generated XML file booksnew. xml:
<? XML version = "1.0"?>
<Book genre = "mystery" publicationdate = "2001" ISBN = "123456789">
<Title> case of the missing cookie </title>
<Author>
<Name> Cookie Monster </Name>
</Author>
<Price> 9.99 </price>
</Book>
It can be seen that there is a start method and end method (writestartelement and writeendelement) in the XML document, and other dedicated Writing Method: writecdata can enter a CDATA; writecomment writes comments in the correct XML format. Writechars writes the content of the character buffer.
Create a document using. Net Dom and xmldocument
private xmldocument Doc = new xmldocument ();
private void button2_click ( Object sender, system. eventargs e)
{< br> xmldeclaration newdec = Doc. createxmldeclaration ("1.0", null, null);
Doc. appendchild (newdec);
xmlelement newroot = Doc. createelement ("newbookstore");
Doc. appendchild (newroot);
// create a new book element
xmlelement newbook = Doc. createelement ("book");
// create and set the attributes of the book element
newbook. setattribute ("genre", "mystery");
newbook. setattribute ("publicationdate", "2001");
newbook. setattribute ("ISBN", "123456789");
// create a title element
xmlelement newtilte = Doc. createelement ("title");
newtilte. innertext = "case of the missing cookie";
newbook. appendchild (newtilte);
// creates an author element
xmlelement newauthor = Doc. createelement ("author");
newbook. appendchild (newauthor);
Xmlelement newname = Doc. createelement ("name ");
Newname. innertext = "C. Monster ";
Newauthor. appendchild (newname );
Xmlelement newprice = Doc. createelement ("price ");
Newprice. innertext = "9.95 ";
Newbook. appendchild (newprice );
Doc. documentelement. appendchild (newbook );
Xmltextwriter TR = new xmltextwriter ("booksedit. xml", null );
Tr. Formatting = formatting. indented;
Doc. writecontentto (TR );
Tr. Close ();
}
code generated documents:
case of the missing cookie </ title>
C. monster
9.95