標籤:nbsp document pos 控制 exists web 排序 ret 儲存
WebService是一種跨程式設計語言和跨作業系統平台的遠程調用技術,簡單來說就是將資料存放區到項目的檔案夾下
.NET中基於DOM核心類
XmlDocument 表示一個XML文檔
XmlNode表示XML文檔中的單個節點
XmlNodeList表示排序節點集合
XmlElement表示一個元素
XmlAttribyte 表示一個屬性
XmlAttribyteCollection表示元素節點的屬性集合
XmlText表示元素或屬性的文本類容
-------------------------------------------------------------------------------------------------------------------------------------
在該控制器中寫入如下的添加刪除查詢代碼
[HttpPost] public void Index(FormCollection F) { string xmlPath = Server.MapPath("~/A/") + "_Class.xml"; XmlDocument doc; try { string Id = F["Id"]; string Name = F["Name"]; string Age = F["Age"]; string Sex = F["Sex"]; string Phone=F["Phone"]; if(!System.IO.File.Exists(xmlPath)) { //建立XML文檔對象 doc = new XmlDocument(); //建立XML文檔描述 XmlDeclaration del = doc.CreateXmlDeclaration("1.0", "utf-8", null); //建立根節點 XmlNode root = doc.CreateNode(XmlNodeType.Element, "Class", null); //在文檔中添加描述 doc.AppendChild(del); //在文檔中添加根節點 doc.AppendChild(root); doc.Save(xmlPath); } //建立XML文檔對象 doc = new XmlDocument(); //讀取指定的XML檔案 doc.Load(xmlPath); //讀取XML中的根節點 XmlElement element = doc.DocumentElement; //建立子節點 XmlElement Stu = doc.CreateElement("Stu"); //設定XML文本值 Stu.InnerText = Name; //設定XML節點屬性 Stu.SetAttribute("Id", Id); Stu.SetAttribute("Sex", Sex); Stu.SetAttribute("Age", Age); Stu.SetAttribute("Phone", Phone); //在根節點中添加子節點 element.AppendChild(Stu); //儲存Xml文檔到指定路徑 doc.Save(xmlPath); Response.Write("<script>alert(‘添加成功!‘);window.location.href = ‘/Home/Index‘;</script>"); } catch (Exception ex) { Response.Write("<script>alert(‘添加失敗!‘);window.location.href = ‘/Home/Index‘;</script>"); } } public ActionResult SelAndDel(string id = "0") { if (id != "0") { //進行刪除操作 string xmlPath = Server.MapPath("~/A/") + "_Class.xml"; XmlDocument doc = new XmlDocument(); doc.Load(xmlPath); XmlElement element = doc.DocumentElement; XmlNode node = doc.SelectSingleNode(string.Format("/Class/Stu[@id=‘{0}‘]",id)); node.ParentNode.RemoveChild(node); doc.Save(xmlPath); } else { string xmlPath = Server.MapPath("~/A/") + "_Class.xml"; StringBuilder sb = new StringBuilder(); XmlDocument doc = new XmlDocument(); doc.Load(xmlPath); XmlElement element = doc.DocumentElement; //遍曆根節點下的所有子節點 foreach (XmlElement item in element.ChildNodes) { sb.Append(string.Format(@"<tr class=‘odd gradeX‘> <td>{0}</td> <td>{1}</td> <td class=‘hidden-480‘>{2}</td> <td class=‘hidden-480‘>{3}</td> <td class=‘center hidden-480‘>{4}</td> <td><a href=‘/Home/SelAndDel/{5}‘>刪除</td> </tr>", item.Attributes["Id"].Value, item.InnerText,item.Attributes["Age"].Value, item.Attributes["Sex"].Value, item.Attributes["Phone"].Value, item.Attributes["Id"].Value) ); } ViewBag.tableText = sb.ToString(); } return View(); }
在視圖頁面顯示內容的地方寫上
@Html.Raw(ViewBag.tableText.ToString())//將在控制器中寫的HTML代碼字串轉換成HTML代碼在前台顯示執行
添加成功後就會在你指定的檔案夾下產生這個文檔將你輸入的值儲存下來
<?xml version="1.0" encoding="utf-8"?><Class> <Stu Id="1" Sex="女" Age="1" Phone="1">1</Stu> <Stu Id="0" Sex="女" Age="0" Phone="0">0</Stu></Class>
WebService的簡單運用添加刪除