首页 > 代码库 > xml文件的增删改读

xml文件的增删改读

最近学习了利用XmlDocument对象对xml进行增删改读操作,就写了一个小的例子记录下来,加深印象,以后忘了也可以找出来看看。

xml文件:

技术分享
 1 <?xml version="1.0" encoding="utf-8"?> 2 <Users> 3   <User Id="1"> 4     <Name>吴奇隆</Name> 5     <Sex>1</Sex> 6     <Phone>888888</Phone> 7   </User> 8   <User Id="2"> 9     <Name>刘诗诗</Name>10     <Sex>0</Sex>11     <Phone>666999</Phone>12   </User>13   <User Id="3">14     <Name>刘德华</Name>15     <Sex>1</Sex>16     <Phone>999999</Phone>17   </User>18   <User Id="4">19     <Name>王祖贤</Name>20     <Sex>0</Sex>21     <Phone>888899</Phone>22   </User>23   <User Id="5">24     <Name>吴倩莲</Name>25     <Sex>0</Sex>26     <Phone>888999</Phone>27   </User>28   <User Id="6">29     <Name>张卫健</Name>30     <Sex>1</Sex>31     <Phone>666888</Phone>32   </User>33   <User Id="7">34     <Name>关之琳</Name>35     <Sex>0</Sex>36     <Phone>888666</Phone>37   </User>38   <User Id="8">39     <Name>张敏</Name>40     <Sex>0</Sex>41     <Phone>888866</Phone>42   </User>43   <User Id="9">44     <Name>梁朝伟</Name>45     <Sex>1</Sex>46     <Phone>888889</Phone>47   </User>48   <User Id="10">49     <Name>李连杰</Name>50     <Sex>1</Sex>51     <Phone>888886</Phone>52   </User>53   <User Id="11">54     <Name>袁洁莹</Name>55     <Sex>0</Sex>56     <Phone>666999</Phone>57   </User>58 </Users>
View Code

xml文件对应的类:

技术分享
1  public class User2     {3         public int Id { get; set; }4         public string Name { get; set; }5         public int Sex { get; set; }6         public string Phone { get; set; }7 8     }
View Code

前台页面用的是Bootstrap Table

前台代码:

技术分享
  1 <!DOCTYPE html>  2   3 <html>  4 <head>  5     <meta name="viewport" content="width=device-width" />  6     <title>Index</title>  7     <link href="~/scripts/bootstrap-table/css/bootstrap.css" rel="stylesheet" />  8     <link href="~/scripts/bootstrap-table/css/bootstrap-table.css" rel="stylesheet" />  9     <script src="~/scripts/bootstrap-table/js/jquery-1.10.2.js"></script> 10     <script src="~/scripts/bootstrap-table/js/bootstrap.js"></script> 11     <script src="~/scripts/bootstrap-table/js/bootstrap-table.js"></script> 12     <script src="~/scripts/bootstrap-table/js/bootstrap-table-zh-CN.js"></script> 13     <script type="text/javascript"> 14         $(function () { 15             $("#table").bootstrapTable({ 16                 toolbar: #toolbar,//工具栏 17                 pagination: true,//是否显示分页条 18                 pageNumber: 1,//首页页码 19                 pageSize: 10,//每页条数 20                 pageList: [10, 20, 30],//可供选择的页面数据条数 21                 url: /UserManager/GetUsers,//获取数据的url 22                 columns: [ 23                     { 24                         checkbox: true//设置复选框 25                     }, 26                     { 27                     field: Id, 28                     title: 编号 29                 }, 30                { 31                    field: Name, 32                    title: 姓名 33                }, { 34                    field: Sex, 35                    title: 性别, 36                    formatter: function (value, row, index) { 37                        if (value == "1") { 38                            return ; 39                        } else { 40                            return ; 41                        } 42                    } 43                }, { 44                    field: Phone, 45                    title: 电话 46                }, { 47                    field: operate, 48                    title: 操作, 49                    formatter: function (value,row,index) { 50                        return <a href="javascript:void(0)" onclick="deleteUser( + row.Id + )">删除</a> 51                    } 52                }] 53             }); 54         }); 55         //删除 56         function deleteUser(id) { 57             if (confirm("你确定要删除吗?")) { 58                 $.get("/UserManager/DeleteUser?Id=" + id, null, function (data) { 59                     if (data == "ok") { 60                         $("#table").bootstrapTable(refresh); 61                     } else { 62                         alert("删除失败!"); 63                     } 64                 }) 65             }           66         } 67         //添加 68         function Add() { 69             var id = $("#uid").val(); 70             var name = $("#name").val(); 71             var sex = $("#sex").val(); 72             var phone = $("#phone").val(); 73             $.post("/UserManager/AddUser", {Id:id, Name: name, Sex: sex, Phone: phone }, function (data) { 74                 if (data == "ok") { 75                     $(#addModal).modal(hide); 76                     $("#table").bootstrapTable(refresh); 77                     $("#uid").val(""); 78                     $("#name").val(""); 79                     $("#sex").val(""); 80                     $("#phone").val(""); 81                 } else { 82                     alert("添加失败!"); 83                 } 84             }); 85         } 86         //修改 87         function Edit() {             88             var id = $("#editId").val(); 89           var name=$("#editName").val(); 90            var sex= $("#editSex").val(); 91            var phone = $("#editPhone").val(); 92            $.post("/UserManager/EditUser", { Id: id, Name: name, Sex: sex, Phone: phone }, function (data) { 93                if (data == "ok") { 94                    $(#editModal).modal(hide); 95                    $("#table").bootstrapTable(refresh); 96                    $("#editId").val(""); 97                    $("#editName").val(""); 98                    $("#editSex").val(""); 99                    $("#editPhone").val("");100                } else {101                    alert("修改失败!");102                }103            });104         }105         //显示修改106         function showEdit() {107             var row = $("#table").bootstrapTable(getSelections);108             if (row.length<=0) {109                 alert("请选择你要修改的行!");110                 return;111             }112             if (row.length > 1) {113                 alert("每次只能修改一行数据!");114                 return;115             }116             $("#editId").val(row[0].Id);117             $("#editName").val(row[0].Name);118             $("#editSex").val(row[0].Sex);119             $("#editPhone").val(row[0].Phone);120             $("#editModal").modal(show);121         }122         //批量删除123         function deleteRows() {124             var row = $(#table).bootstrapTable(getSelections);125             if (row.length > 0) {126             if (confirm("你确定要删除吗?")) {               127                     var ids = $.map($(#table).bootstrapTable(getSelections), function (row) {128                         return row.Id;129                     });130                     $.post("@Url.Action("DeleteUsers", "UserManager")", { ids:ids }, function (data) {131                         if (data == "ok") {132                             $(#table).bootstrapTable(remove, { field: Id, values: ids });133                         }  else {134                             alert("删除失败");135                         }136                     });137                 } 138             } else {139                 alert("请选择你要删除的行!");140             }141         }142     </script>143 </head>144 <body>145     <table id="table"></table>146     <div>147         <!--添加 Modal -->148         <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">149             <div class="modal-dialog">150                 <div class="modal-content">151                     <div class="modal-header">152                         <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>153                         <h4 class="modal-title" id="myModalLabel">添加用户</h4>154                     </div>155                     <div class="modal-body">156                         <label for="name">编号:</label>157                         <input type="text" class="form-control" id="uid" placeholder="请输入编号">158                             <label for="name">姓名:</label>159                             <input type="text" class="form-control" id="name" placeholder="请输入姓名">160                             <label for="name">性别:</label>161                             <select id="sex" class="form-control">162                             <option selected>--请选择--</option>163                             <option value="1"></option>164                             <option value="0"></option>165                             </select>166                             <label for="name">电话:</label>167                             <input type="text" class="form-control" id="phone" placeholder="请输入电话">168                         </div>169                         <div class="modal-footer">170                             <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>171                             <button type="button" class="btn btn-primary" onclick="Add();">保存</button>172                         </div>173                     </div><!-- /.modal-content -->174             </div><!-- /.modal-dialog -->175         </div><!-- /.modal -->176     </div>177     <div>178         <!-- 修改Modal -->179         <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">180             <div class="modal-dialog">181                 <div class="modal-content">182                     <div class="modal-header">183                         <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>184                         <h4 class="modal-title" id="myModalLabel">修改用户</h4>185                     </div>186                     <div class="modal-body">187                         <label for="name">编号:</label>188                         <input type="text" class="form-control" readonly id="editId" >189                         <label for="name">姓名:</label>190                         <input type="text" class="form-control" id="editName" >191                         <label for="name">性别:</label>192                         <select id="editSex" class="form-control">193                             <option>--请选择--</option>194                             <option value="1"></option>195                             <option value="0"></option>196                         </select>197                         <label for="name">电话:</label>198                         <input type="text" class="form-control" id="editPhone">199                     </div>200                     <div class="modal-footer">201                         <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>202                         <button type="button" class="btn btn-primary" onclick="Edit();">保存</button>203                     </div>204                 </div><!-- /.modal-content -->205             </div><!-- /.modal-dialog -->206         </div><!-- /.modal -->207     </div>208 209 210     <div class="btn-group" id="toolbar">211         <button type="button" class="btn btn-default glyphicon glyphicon-pencil"  onclick="showEdit();">修改</button>212         <button type="button" class="btn btn-default glyphicon glyphicon-trash" onclick="deleteRows();">批量删除</button>213         <button type="button" class="btn btn-default glyphicon glyphicon-plus" data-toggle="modal" data-target="#addModal" >添加</button>214     </div>215 216 </body>217 </html>
View Code

后台代码:

技术分享
  1   public class UserManagerController : Controller  2     {  3         #region 数据展示页面  4         /// <summary>  5         /// 数据展示页面  6         /// </summary>  7         /// <returns></returns>  8         public ActionResult Index()  9         { 10             return View(); 11         }  12         #endregion 13         #region 读取xml数据 14         /// <summary> 15         /// 读取xml数据 16         /// </summary> 17         /// <returns></returns> 18         public ActionResult GetUsers() 19         { 20             List<User> list = new List<User>(); 21             string path = Server.MapPath("~/xmlfile/User.xml"); 22             //创建xml文档对象 23             XmlDocument doc = new XmlDocument(); 24             //加载xml数据 25             doc.Load(path); 26             //获取xml根节点 27             XmlElement root = doc.DocumentElement; 28             //判断是否有子节点 29             if (root.HasChildNodes) 30             { 31                 foreach (XmlNode node in root) 32                 { 33                     User user = new User(); 34                     //获取当前节点属性Id的值 35                     user.Id = Convert.ToInt32(node.Attributes["Id"].Value); 36                     if (node.SelectSingleNode("Name") != null) 37                     {   //获取节点值 38                         user.Name = node["Name"].InnerText; 39                     } 40                     if (node.SelectSingleNode("Sex") != null) 41                     { 42                         user.Sex = Convert.ToInt32(node["Sex"].InnerText); 43                     } 44                     if (node.SelectSingleNode("Phone") != null) 45                     { 46                         user.Phone = node["Phone"].InnerText; 47                     } 48                     list.Add(user); 49                 } 50             } 51             return Json(list, JsonRequestBehavior.AllowGet); 52         }  53         #endregion 54         #region 添加 55         /// <summary> 56         /// 添加 57         /// </summary> 58         /// <param name="user"></param> 59         /// <returns></returns> 60         public ActionResult AddUser(User user) 61         { 62             try 63             { 64                 XmlDocument doc = new XmlDocument(); 65                 string path = Server.MapPath("~/xmlfile/User.xml"); 66                 doc.Load(path); 67                 XmlElement root = doc.DocumentElement; 68                 XmlElement xElement = doc.CreateElement("User"); 69                 xElement.SetAttribute("Id", user.Id.ToString()); 70                 root.AppendChild(xElement); 71                 XmlElement Name = doc.CreateElement("Name"); 72                 Name.InnerText = user.Name; 73                 xElement.AppendChild(Name); 74                 XmlElement Sex = doc.CreateElement("Sex"); 75                 Sex.InnerText = user.Sex.ToString(); 76                 xElement.AppendChild(Sex); 77                 XmlElement Phone = doc.CreateElement("Phone"); 78                 Phone.InnerText = user.Phone; 79                 xElement.AppendChild(Phone); 80                 doc.Save(path); 81                 return Content("ok"); 82             } 83             catch 84             { 85                 return Content("error"); 86             } 87  88         }  89         #endregion 90         #region 删除 91         /// <summary> 92         /// 删除 93         /// </summary> 94         /// <param name="Id"></param> 95         /// <returns></returns> 96         public ActionResult DeleteUser(int Id) 97         { 98             XmlDocument doc = new XmlDocument(); 99             string path = Server.MapPath("~/xmlfile/User.xml");100             doc.Load(path);101             XmlElement root = doc.DocumentElement;102             XmlNode user = doc.SelectSingleNode("/Users/User[@Id=‘" + Id + "‘]");103             if (user != null)104             {105                 root.RemoveChild(user);106 107             }108             doc.Save(path);109             return Content("ok");110         }111         #endregion112         #region 修改113         /// <summary>114         /// 修改115         /// </summary>116         /// <param name="user"></param>117         /// <returns></returns>118         public ActionResult EditUser(User user)119         {120             XmlDocument doc = new XmlDocument();121             string path = Server.MapPath("~/xmlfile/User.xml");122             doc.Load(path);123             // XmlElement root = doc.DocumentElement;124             XmlNode xNode = doc.SelectSingleNode("/Users/User[@Id=‘" + user.Id + "‘]");125             if (xNode != null)126             {127                 // xNode.Attributes["Id"].Value = http://www.mamicode.com/user.Id.ToString();>128                 if (xNode["Name"] != null)129                 {130                     xNode["Name"].InnerText = user.Name;131                 }132                 if (xNode["Sex"] != null)133                 {134                     xNode["Sex"].InnerText = user.Sex.ToString();135                 }136                 if (xNode["Phone"] != null)137                 {138                     xNode["Phone"].InnerText = user.Phone;139                 }140             }141             doc.Save(path);142             return Content("ok");143         }144         #endregion 145         #region 批量删除146         /// <summary>147         /// 批量删除148         /// </summary>149         /// <param name="ids"></param>150         /// <returns></returns>151         public ActionResult DeleteUsers(int[] ids)152         {153 154             XmlDocument doc = new XmlDocument();155             string path = Server.MapPath("~/xmlfile/User.xml");156             doc.Load(path);157             XmlElement root = doc.DocumentElement;158             try159             {160                 for (int i = 0; i < ids.Length; i++)161                 {162                     XmlNode xNode = doc.SelectSingleNode("/Users/User[@Id=‘" + ids[i] + "‘]");163                     if (xNode != null)164                     {165                         root.RemoveChild(xNode);166                     }167                 }168                 doc.Save(path);169                 return Content("ok");170             }171             catch172             {173                 return Content("no");174             }175 176         } 177         #endregion178     }
View Code

最终显示效果:

技术分享

添加页面:

技术分享

 

修改页面:

技术分享

 

xml文件的增删改读