Thứ Ba, 15 tháng 1, 2008

Writing XML

I have some examples for you: First write the XML file like:
// Write Example:
private void XmlNewData()
{
FileStream fsNew = File.Create("data.xml");
XmlTextWriter XmlWriter = new XmlTextWriter(fsNew, null);
XmlWriter.Formatting = Formatting.Indented;
WriteXmlFormat(writer);
XmlWriter.Flush();
XmlWriter.Close();
}
WriteXmlFormat(writer); will call the method where the xml file is formatted, this method looks like:
// Method for designing the XML tree called by Update and Write example:
private void WriteXmlFormat(XmlWriter writer)
{
// Here you could put code to get the data from the database and drop it in the dsData dataset.
writer.WriteStartElement("data");
// Looping al rows in de dataset and specified table
foreach (DataRow drItem in dsData.Tables["table1"].Rows)
{
writer.WriteStartElement("row");
writer.WriteAttributeString("column1", drItem["column1"]);
writer.WriteEndElement();
}
writer.WriteEndElement();
}In the following example you read the XML file into a dataset and then fill the specified dropdownlist: // Read Example:
private void ReadDataIntoListBox()
{
DataSet dsData = new DataSet();
dsData.ReadXml("data.xml");
foreach(DataRow dr in dsData.Tables["rows"].Rows)
{
ddlSome.Items.Add(dr["colomname"]);
}
}
And if you want to update:
// Update example:
private void XmlUpdateData()
{
File.Delete("data.xml");
FileStream fsNew = File.Create("data.xml");
XmlTextWriter XmlWriter = new XmlTextWriter(fsNew, null);
XmlWriter.Formatting = Formatting.Indented;
WriteQuote(writer);
XmlWriter.Flush();
XmlWriter.Close();
}

Không có nhận xét nào: