背景:
项目中在启动一个程序时需要调用XML文档中的数据;每次调用一组数据,然后再查看这次数据的结果。由于每次人工输入游戏数据太费精力因此做了一个asp.net自动调用XML的小程序
XML文档格式:
<?xml version="1.0" encoding="gb2312"?><Tasks><Task Type="1" ReadFlag="0"><TaskName>安装游戏</TaskName><UserName /><GameID>777</GameID><GameName>小红帽</GameName><LocalInstallPath>C:\Documents and Settings\Administrator\桌面\演示版本\BBM</LocalInstallPath><TotalBytes>0</TotalBytes><AddedTime>2008-05-15 18:17:23</AddedTime></Task></Tasks>
自动生成XML文档的代码:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Build_Click(object sender, EventArgs e)
{
// 创建XmlTextWriter类的实例对象
XmlTextWriter textWriter = new XmlTextWriter("C:/Documents and Settings/Administrator/桌面/演示版本/Task.xml", Encoding.GetEncoding("GB2312"));
//Write the XML delcaration.
textWriter.WriteStartDocument();
// 创建根节点
textWriter.WriteStartElement("Tasks");
textWriter.WriteStartElement("Task");
textWriter.WriteAttributeString("Type", "1");
textWriter.WriteAttributeString("ReadFlag", "0");
// 创建新节点
textWriter.WriteStartElement("TaskName");
textWriter.WriteString("安装游戏");
textWriter.WriteEndElement();
textWriter.WriteStartElement("UserName");
textWriter.WriteString("");
textWriter.WriteEndElement();
textWriter.WriteStartElement("GameID");
textWriter.WriteString(GameID.Text);
textWriter.WriteEndElement();
textWriter.WriteStartElement("GameName");
textWriter.WriteString(GameName.Text);
textWriter.WriteEndElement();
textWriter.WriteStartElement("LocalInstallPath");
textWriter.WriteString("C:\\Documents and Settings\\Administrator\\桌面\\演示版本\\"+LocalInstallPath.Text);
textWriter.WriteEndElement();
textWriter.WriteStartElement("TotalBytes");
textWriter.WriteString("0");
textWriter.WriteEndElement();
textWriter.WriteStartElement("AddedTime");
textWriter.WriteString("2008-05-15 18:17:23");
textWriter.WriteEndElement();
// 关闭根节点.
textWriter.WriteEndElement();
textWriter.WriteEndElement();
// 关闭textWriter
textWriter.Close();
//显示XML文件生成成功
Response.Write("生成文件成功!");
}
}
使用button按钮触发生成XML的界面:
GameID 请输入GameID
GameName 请输入GameName
LocalInstallPath 请输入LocalInstallPath