首页 > 代码库 > C#对XML进行操作(添加、修改)

C#对XML进行操作(添加、修改)

XML文档内容如下:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <first id="100" name="系统设置">
    <second id="101" show="1" page="/sys/fn" name="功能菜单" querystring="" />
    <second id="102" show="1" page="/bidding/detail" name="权限管理" querystring="" />
    <second id="103" show="0" page="/sys/fnsecondedit" name="编辑" querystring="" />
    <second id="104" show="0" page="/sys/fnfirstedit" name="编辑父类" querystring="" />
  </first>
  <first id="200" name="账户设置">
    <second id="201" show="1" page="/bidding/detail" name="修改密码" querystring="" />
    <second id="202" show="1" page="/account/user" name="个人信息" querystring="" />
  </first>
</root>

给XML指定的标签内添加标签

string xmlpath = "/xml/role.config";
XDocument doc = XDocument.Load(Server.MapPath(xmlpath));
XElement root = doc.Element("root");
XElement first = new XElement("first");
first.Add(new XAttribute("id", id), new XAttribute("name", name));
root.Add(first);
doc.Save(Server.MapPath(xmlpath));

修改指定的标签

string xmlpath = "/xml/role.config";
XDocument doc = XDocument.Load(Server.MapPath(xmlpath));
XElement x = doc.Descendants("first").FirstOrDefault(t => t.Attribute("id").Value =http://www.mamicode.com/= id.ToString());"name").Value = http://www.mamicode.com/name;>

  

C#对XML进行操作(添加、修改)