.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);
}
修改和添加是一样的就是重新在赋值一下在保存一下文档
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。