C#对XML的操作,利用DataSet对XML进行操作。
//创建一个数据集
DataSet dsTradeNews = new DataSet();
//读取XML文件用于绑定到DataGrid上
dsTradeNews.ReadXml(@"D:\CorpInfo.xml",XmlReadMode.Auto);
//创建一个表
DataTable dtTradeNews = new DataTable("TradeNews");
//创建列
DataColumn dcSimpleName = new DataColumn("SimpleName",Type.GetType("System.String"));
DataColumn dcCode = new DataColumn("Code",Type.GetType("System.String"));
//将列加入到表中
dtTradeNews.Columns.Add(dcSimpleName);
dtTradeNews.Columns.Add(dcCode);
//创建行并为每列赋值
DataRow drTradeNew = dtTradeNews.NewRow();
drTradeNew["SimpleName"] = "公司";
drTradeNew["Code"] = "888888";
//将表加入数据集中
dsTradeNews.Tables.Add(dtTradeNews);
//生成XML文件或覆盖XML文件
try
{
dsTradeNews.WriteXml(@"D:\CorpInfo.xml");
}
catch(Exception ex)
{
Response.Write("生成XML文件产生异常:" + ex.Message);
return ;
}
dgTradeNews.DataSource = dsTradeNews.Tables["TradeNews"].DefaultView;
dgTradeNews.DataBind();
DataSet dsTradeNews = new DataSet();
//读取XML文件用于绑定到DataGrid上
dsTradeNews.ReadXml(@"D:\CorpInfo.xml",XmlReadMode.Auto);
//创建一个表
DataTable dtTradeNews = new DataTable("TradeNews");
//创建列
DataColumn dcSimpleName = new DataColumn("SimpleName",Type.GetType("System.String"));
DataColumn dcCode = new DataColumn("Code",Type.GetType("System.String"));
//将列加入到表中
dtTradeNews.Columns.Add(dcSimpleName);
dtTradeNews.Columns.Add(dcCode);
//创建行并为每列赋值
DataRow drTradeNew = dtTradeNews.NewRow();
drTradeNew["SimpleName"] = "公司";
drTradeNew["Code"] = "888888";
//将表加入数据集中
dsTradeNews.Tables.Add(dtTradeNews);
//生成XML文件或覆盖XML文件
try
{
dsTradeNews.WriteXml(@"D:\CorpInfo.xml");
}
catch(Exception ex)
{
Response.Write("生成XML文件产生异常:" + ex.Message);
return ;
}
dgTradeNews.DataSource = dsTradeNews.Tables["TradeNews"].DefaultView;
dgTradeNews.DataBind();