|
The XmlWriter class contains the functionality to write to XML documents. XmlWriter is an abstract base class and is a super class of XmlTextWriter and XmlNodeWriter classes which are used to write the XML documents. This class has many WriteXXX methods to write paired, unpaired and empty XML elements. Some of these methods are used in a start and end pair. For example, to write an element, you need to call WriteStartElement then write a string followed by WriteEndElement.
Example: Demonstrate Writing to XML file
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace _CSharpApplication
{
public partial class Form12 : Form
{
public Form12()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{
try
{
XmlTextWriter xmlWRITER = new XmlTextWriter ( "C:\\writeEmployeeRecordInXML1.xml" , null );
xmlWRITER.WriteStartDocument();
xmlWRITER.WriteComment( "Commentss: START DATE : 21-OCT-07" );
xmlWRITER.WriteComment( "Commentss: WRITE XML DOCUMENT" );
xmlWRITER.WriteStartElement( "EMPLOYEE" );
xmlWRITER.WriteStartElement( "r" , "RECORD" , "urn:record" );
xmlWRITER.WriteStartElement( "EMPLOYEE NAME" , "" );
xmlWRITER.WriteString(txtName.Text);
xmlWRITER.WriteEndElement();
xmlWRITER.WriteStartElement( "EMPLOYEE ADDRESS" , "" );
xmlWRITER.WriteString(txtAddress.Text);
xmlWRITER.WriteEndElement();
//WRITE ANOTHER ELEMENT
xmlWRITER.WriteStartElement( "EMPLOYEE Date Of Birth" , "" );
xmlWRITER.WriteString(txtDOB.Text);
xmlWRITER.WriteEndElement();
//WRITE ANOTHER ELEMENT
xmlWRITER.WriteStartElement( "EMPLOYEE Qualification" ,"" );
xmlWRITER.WriteString(txtQual.Text);
xmlWRITER.WriteEndElement();
char [] ch = new char [3];
ch[0] = 'X' ;
ch[1] = 'M' ;
ch[2] = 'L' ;
xmlWRITER.WriteStartElement( "WRITING CHARACTER IN XML DOCUMENT" );
xmlWRITER.WriteChars(ch, 0, ch.Length);
xmlWRITER.WriteEndElement();
xmlWRITER.WriteEndDocument();
xmlWRITER.Close();
MessageBox.Show( "*********DONE***********" );
}
catch ( Exception ex) {
(ex.Source);
}
}
}}

Clicking on the “Writing XML Document”

This will generate a Xml file that contains the contents as given below:
“writeEmployeeRecordInXML.xml”
<?xml version="1.0"?>
<!--Commentss: START DATE : 21-OCT-07-->
<!--Commentss: WRITE XML DOCUMENT-->
<EMPLOYEE>
<r:RECORD xmlns:r="urn:record">
<EMPLOYEE NAME>Joseph</EMPLOYEE NAME>
<EMPLOYEE ADDRESS>Terry</EMPLOYEE ADDRESS>
<EMPLOYEE Date Of Birth>17-7-1981</EMPLOYEE Date Of Birth>
<EMPLOYEE Qualification>MBA</EMPLOYEE Qualification>
<WRITING CHARACTER IN XML DOCUMENT>XML</WRITING CHARACTER IN XML DOCUMENT>
</r:RECORD>
</EMPLOYEE> |