ASP.NET XML读取、增加、修改和删除操作

阅读更多

C#—XML读取、增加、修改和删除操作
1.xml文件格式如下:



1.读取
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath(@"Projects.xml"));
DataTable dt = ds.Tables[0];
return dt;
//得到的datable在前台进行循环输出,省略...
//文字加粗
//文字底部加横线

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 + "$" + txtProjectPath.Text + "$" + 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 + "$" + txtProjectPath1.Text + "$" + 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);
   }
}

 

 

你可能感兴趣的:(ASP.net,XML,.net,ASP,VSS)