.net 操作XML(1)添加,删除,修改,查询

查询xml这个是我获取前台菜单的xml

private void getMenu(string[] cidlist, string[] idlist)
{
//获取菜单文件
string sPath = System.Web.HttpContext.Current.Request.MapPath("Menu/MenuFile.xml");
//加载
xml.Load(sPath);
for (int i = 0; i < cidlist.Length; i++)
{
XmlNode thisNode = xml.DocumentElement.SelectSingleNode("/Menus/menu[@cid=" + cidlist[i].ToString() + "]");
if (thisNode != null)
{
html += "<li class=''><a href='javascript:;'><i class='" + thisNode.Attributes["icon"].Value + "'></i> <span class='title'>" + thisNode.Attributes["heard"].Value + "</span><span class='arrow '></span></a><ul class='sub-menu'>";
for (int j = 0; j < idlist.Length; j++)
{
XmlNode thisNode1 = xml.DocumentElement.SelectSingleNode("/Menus/menu[@cid=" + cidlist[i].ToString() + "]/li[@id=" + idlist[j].ToString() + "]");
if (thisNode1 != null)
{
html += "<li><a onclick='gotosrc(this)' src='" + thisNode1.Attributes["src"].Value + "' target='main'>" + thisNode1.Attributes["tittle"].Value + "</a></li>";
}
else
{
continue;
}
}
html += "</ul></li>";
}
}
}

 

 

添加:

string name = context.Request.Form["name"].ToString();
string strcid = context.Request.Form["strcid"].ToString();
string strtid = context.Request.Form["strtid"].ToString();
XmlDocument xml = new XmlDocument();
string sPath = System.Web.HttpContext.Current.Request.MapPath("../Menu/RoleFile.xml");
xml.Load(sPath);
XmlNode root = xml.SelectSingleNode("Roles");
XmlNodeList xnl = root.ChildNodes;
bool flag = false;
foreach (XmlNode item in xnl)
{
XmlElement xe = (XmlElement)item;
if (xe.GetAttribute("roleName") == name)
{
flag = true;
}
else
{
continue;
}
}
if (flag == false)
{
XmlElement xe1 = xml.CreateElement("role");
xe1.SetAttribute("roleName", name);
xe1.SetAttribute("cid", strcid);
xe1.SetAttribute("pList", strtid);
root.AppendChild(xe1);
xml.Save(sPath);
context.Response.Write("OK");
}
else
{
context.Response.Write("该角色已存在!");
}

 

删除:

string roleName = context.Request.Form["roleName"].Trim().ToString();
string sPath = System.Web.HttpContext.Current.Request.MapPath("../Menu/RoleFile.xml");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(sPath);
XmlNodeList xnl = xmlDoc.SelectSingleNode("Roles").ChildNodes;
string flag = "NO";
foreach (XmlNode xn in xnl)
{
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute("roleName") == roleName)
{
//xe.RemoveAll();//删除该节点的全部内容
xn.RemoveAll(); //删除该节点
flag = "OK";
break;
}
}
if (flag == "OK")
{
xmlDoc.Save(sPath);
context.Response.Write(flag);
}
else {
context.Response.Write(flag);
}

 

修改和添加是一样的就是重新在赋值一下在保存一下文档

 

posted @ 2015-04-16 11:30  徐本县  阅读(204)  评论(0编辑  收藏  举报