Monday, October 11, 2004

Using XML TextWriter to create an XML file

**********This code sample shows how to use XML text writer to create an XML file********


string XmlFile;
System.IO.DirectoryInfo directoryInfo;
System.IO.DirectoryInfo directoryXML;

//Get the applications startup path
directoryInfo = System.IO.Directory.GetParent(Application.StartupPath);

//Set the output path
if (directoryInfo.Name.ToString() == "bin")
{
directoryXML = System.IO.Directory.GetParent(directoryInfo.FullName);
XmlFile = directoryXML.FullName + "\\" + OutputFileName.Text;
}
else
{
XmlFile = directoryInfo.FullName + "\\" + OutputFileName.Text;
}

//create the xml text writer object by providing the filename to write to
//and the desired encoding. If the encoding is left null, then the writer
//assumes UTF-8.
XmlTextWriter XmlWtr = new System.Xml.XmlTextWriter(XmlFile,null);

//set the formatting option of the xml file. The default indentation is 2 character spaces.
//To change the default, use the Indentation property to set the number of IndentChars to use
//and use the IndentChar property to set the character to use for indentation, such as the
//tab character. Here the default is used.
XmlWtr.Formatting=Formatting.Indented;

//begin to write the xml document. This creates the xml declaration with the version attribute
//set to "1.0".
XmlWtr.WriteStartDocument();

//start the first element.
XmlWtr.WriteStartElement("customers");

//create our first customer element.
//this is a child element of the customers element.
XmlWtr.WriteStartElement("customer");

//writes the entire element with the specified element name and
//string value respectively.
XmlWtr.WriteElementString("name", "Kevin Anders");
XmlWtr.WriteElementString("phone", "555.555.5555");

//end the customer element.
XmlWtr.WriteEndElement();

//create another customer.
XmlWtr.WriteStartElement("customer");
XmlWtr.WriteElementString("name", "Staci Richard");
XmlWtr.WriteElementString("phone", "555.122.1552");

//end the second customer element.
XmlWtr.WriteEndElement();

//end the customers element.
XmlWtr.WriteEndElement();

//now end the document.
XmlWtr.WriteEndDocument();

//now flush the contents of the stream.
XmlWtr.Flush();

//close the text writerj and write the xml file.
XmlWtr.Close();
statusBar1.Text = "Output file has been written";
}
}

No comments: