2. Writing XML with the XmlWriter Class
• XmlWriterSettings.CheckCharacters property
configures the XmlWriter to check for illegal
characters in text nodes and XML names, as well as
check the validity of XML names . An exception is
thrown if an invalid character is detected .
• XmlWriterSettings.ConformanceLevel property
configures the XmlWriter to guarantee that the
stream complies with the conformance level that is
specified. For example, the XML may be set to
conform to a document or document fragment.
• XmlWriter. WriteValue method is used to write data
to the XML stream as a CLR type (int , double , and so
on) without having to first convert it to a string.
3. Write XML Using XmlWriter Class
private void WriteMovie()
{ string[,] movieList = { { "Annie Hall", "Woody Allen" }, {
"Lawrence of Arabia", "David Lean" } };
// (1) Define settings to govern writer actions
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true; settings.IndentChars = (" ");
settings.ConformanceLevel =
ConformanceLevel.Document;
settings.CloseOutput = false;
settings.OmitXmlDeclaration = false;
4. Write XML Using XmlWriter Class
private void WriteMovie()
{
string[,] movieList = { { "Annie Hall", "Woody Allen" }, { "Lawrence of
Arabia", "David Lean" } };
// (1) Define settings to govern writer actions XmlWriterSettings settings
= new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = (" ");
settings.ConformanceLevel =ConformanceLevel.Document;
settings.CloseOutput = false;
settings.OmitXmlDeclaration = false;
5. Write XML Using XmlWriter Class
// (2) Create XmlWriter object XmlWriter writer =
XmlWriter.Create("c:mymovies.xml", settings);
writer.WriteStartDocument();
writer.WriteComment("Output from xmlwriter class");
writer.WriteStartElement("films");
for (int i = 0; i <= movieList.GetUpperBound(0) ; i++)
{
try
{ writer.WriteStartElement("movie");
writer.WriteElementString("Title", movieList[i, 0]);
writer.WriteElementString("Director", movieList[i, 1]);
writer.WriteStartElement("Movie_ID");
writer.WriteValue(i); // No need to convert to string
writer.WriteEndElement();
writer.WriteEndElement();}
9. • .NET also provides XmlTextWriter and
XmlNodeWriter classes as concrete
implementations of the abstract XmlWriter
class
• node writer creates a DOM tree in memory
that can be processed using the many classes
and methods designed for that task.