Read and Write XML File
static void Main()
{
Application.Run(new Form1());
}
private void ReadXMLFileAndFillCombos()
{
try
{
string sStartupPath = Application.StartupPath;
clsSValidator objclsSValidator = new clsSValidator(sStartupPath + @"..\..\..\XMLFile1.xml",
sStartupPath + @"..\..\..\XMLFile1.xsd");
if (objclsSValidator.ValidateXMLFile()) return;
XmlTextReader objXmlTextReader = new XmlTextReader(sStartupPath + @"..\..\..\XMLFile1.xml");
string sName="";
while ( objXmlTextReader.Read() )
{
switch (objXmlTextReader.NodeType)
{
case XmlNodeType.Element:
sName=objXmlTextReader.Name;
break;
case XmlNodeType.Text:
switch(sName)
{
case "BookName":
cboBookName.Items.Add(objXmlTextReader.Value);
break;
case "ReleaseYear":
cboReleaseYear.Items.Add(objXmlTextReader.Value);
break;
case "Publication":
cboPublication.Items.Add(objXmlTextReader.Value);
break;
}
break;
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void Form1_Load(object sender, System.EventArgs e)
{
ReadXMLFileAndFillCombos();
}
private void WriteXMLFileUsingValuesFromCombos()
{
try
{
//XmlTextWriter is used below. This class helps us to write xml on
//many places like stream, console,file etc we are pushing the xml
//on a file. Simply nest the Start & End method and its done
string sStartupPath = Application.StartupPath;
XmlTextWriter objXmlTextWriter = new XmlTextWriter(sStartupPath + @"\selected.xml",null);
objXmlTextWriter.Formatting = Formatting.Indented;
objXmlTextWriter.WriteStartDocument();
objXmlTextWriter.WriteStartElement("MySelectedValues");
objXmlTextWriter.WriteStartElement("BookName");
objXmlTextWriter.WriteString(cboBookName.Text);
objXmlTextWriter.WriteEndElement();
objXmlTextWriter.WriteStartElement("ReleaseYear");
objXmlTextWriter.WriteString(cboReleaseYear.Text);
objXmlTextWriter.WriteEndElement();
objXmlTextWriter.WriteStartElement("Publication");
objXmlTextWriter.WriteString(cboPublication.Text);
objXmlTextWriter.WriteEndElement();
objXmlTextWriter.WriteEndElement();
objXmlTextWriter.WriteEndDocument();
objXmlTextWriter.Flush();
objXmlTextWriter.Close();
MessageBox.Show("The following file has been successfully created\r\n"
+ sStartupPath
+ @"\selected.xml","XML",MessageBoxButtons.OK,MessageBoxIcon.Information );
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void cmdWriteToFile_Click(object sender, System.EventArgs e)
{
WriteXMLFileUsingValuesFromCombos();
}
}