.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 οnclick='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);
}

 

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

 

转载于:https://www.cnblogs.com/anyben/p/4431556.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值