XmlTextWriter、XmlWriter
static void WriteXMLbyXmlWriter(XmlWriter writer, string symbol, double price, double change, long volume)
{
writer.WriteStartElement("Stock");
writer.WriteAttributeString("Symbol", symbol);
writer.WriteElementString("Price", XmlConvert.ToString(price));
writer.WriteElementString("Change", XmlConvert.ToString(change));
writer.WriteElementString("Volume", XmlConvert.ToString(volume));
writer.WriteEndElement();
}
private void CreateXMLFileButton_Click(object sender, System.EventArgs e)
{
// 创建一个表示所要生成的XML文件路径的字符串。如果该路径指向NTFS分区,则需要相关的访问权限。
string filename = @"C:\XML\Stock.xml";
// 创建一个写入XML数据的文件流
System.IO.FileStream myFileStream = new System.IO.FileStream(filename, System.IO.FileMode.Create);
// 使用文件流对象创建一个XmlTextWriter对象
XmlTextWriter myXmlWriter = new XmlTextWriter(myFileStream, System.Text.Encoding.Unicode);
myXmlWriter.Formatting = Formatting.Indented;
try
{
// 使用WriteXMLbyXmlWriter方法把数据写入XmlTextWriter对象中
WriteXMLbyXmlWriter(myXmlWriter, "MSFT", 74.5, 5.5, 49020000);
// 通过Close方法的调用,XmlTextWriter对象的数据最终写入XML文件
myXmlWriter.Close();
Page.Response.Write("生成XML文档成功!");
}
catch
{
Page.Response.Write("生成XML文档失败!请检查路径是否正确,以及是否有写入权限。");
}
}