C#—XML读取、增加、修改和删除操作

 1.xml文件格式如下:

<?xml version="1.0" encoding="utf-8"?>
<projects>
<project name="PlatformFramewo" vss-path="Platform$/Source CodHdt$Pla~1.sln" />
</projects>

1.读取

DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath(@"Projects.xml"));
DataTable dt = ds.Tables[0];
return dt;
//得到的datable在前台进行循环输出,省略...
<tr style="font-weight: bold;"> //文字加粗
<td style="border-bottom: solid 2px gray;"> //文字底部加横线

2.新增

XmlDocument xmlDoc = new XmlDocument();
string Path = Server.MapPath(@"Projects.xml");
xmlDoc.Load(Path);
XmlNode root=xmlDoc.SelectSingleNode("projects");
XmlElement xe1 = xmlDoc.CreateElement("project");
xe1.SetAttribute("name", txtProjectName.Text);
strVssPath = txtProjectVss.Text + "{1}quot; + txtProjectPath.Text + "{1}quot; + txtProjectSln.Text;
xe1.SetAttribute("vss-path",strVssPath);
root.AppendChild(xe1);
xmlDoc.Save(Path);

3.修改

XmlDocument xmlDoc = new XmlDocument();
string Path = Server.MapPath(@"Projects.xml");
xmlDoc.Load(Path);
XmlNodeList nodelist = xmlDoc.SelectSingleNode("projects").ChildNodes;
foreach (XmlNode xn in nodelist)
{
     XmlElement xe = (XmlElement)xn;
     if (xe.GetAttribute("name") == Request["name"].ToString())
     {
         xe.SetAttribute("name", txtProjectName1.Text);
         strVssPath = txtProjectVss1.Text + "{1}quot; + txtProjectPath1.Text + "{1}quot; + txtProjectSln1.Text;
         xe.SetAttribute("vss-path", strVssPath);
         xmlDoc.Save(Path);
      }
   }

4.删除

XmlDocument xmlDoc = new XmlDocument();
string Path = Server.MapPath(@"Projects.xml");
xmlDoc.Load(Path);
XmlNodeList nodelist = xmlDoc.SelectSingleNode("projects").ChildNodes;
foreach (XmlNode xn in nodelist)
{
   XmlElement xe = (XmlElement)xn;
   if (xe.GetAttribute("name") == Request["name"].ToString())
   {
     xn.ParentNode.RemoveChild(xn);
     xmlDoc.Save(Path);
   }
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值