Writing XML Files Using the XmlTextWriter Class, Page 2
Close the File and Perform Cleanup
Once you've finished writing the XML data, close the document. This is typically done with the following calls:writer->WriteEndDocument(); writer->Flush(); writer->Close();
Example
Taking the methods outlined in the previous section, the following bit of C++ calls various XmlTextWriter methods to generate a simple XML file:
XmlTextWriter* writer = new XmlTextWriter(S"test.xml", Encoding::ASCII);
writer->WriteStartDocument(true);
writer->WriteStartElement("Article");
writer->WriteElementString(S"Author", S"Tom Archer");
writer->WriteStartElement(S"Title");
writer->WriteAttributeString(S"lang", S"EN");
writer->WriteString(S"Writing XML Files using the XmlTextWriterClass");
writer->WriteEndElement();
writer->WriteStartElement(S"URL");
writer->WriteCData(S"http:\\\\www.test url&var=value");
writer->WriteEndElement();
writer->WriteEndElement();
writer->WriteEndDocument();
writer->Flush();
writer->Close();
This C++ code will generate the XML shown in Figure 1.

Click here for a larger image.
Looking Ahead
This first installment of the series on using the .NET XML classes demonstrated how easy it is to generate a valid XML file with Managed C++ and the XmlTextWriter class. The next article proceeds to the next logical step: using the XmlTextReader class.About the Author
Tom Archer owns his own training company, Archer Consulting Group, which specializes in educating and mentoring .NET programmers and providing project management consulting. If you would like to find out how the Archer Consulting Group can help you reduce development costs, get your software to market faster, and increase product revenue, contact Tom through his Web site.
0 Comments (click to add your comment)
Networking Solutions
