網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
ASP.NET?MVC創(chuàng)建XML文件并實(shí)現(xiàn)元素增刪改_實(shí)用技巧
作者:Darren?Ji ? 更新時(shí)間: 2022-09-24 編程語(yǔ)言如果創(chuàng)建如下的XML:
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <Students> <Student Id="1"> <Name>darren</Name> </Student> </Students>
創(chuàng)建XML文件
在HomeController中,在根目錄下創(chuàng)建new.xml文件:
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult AddXml()
{
string path = Server.MapPath("~/new.xml");
XDocument doc = new XDocument(
new XDeclaration("1.0","utf-8","yes"),
new XElement("Students",new XElement("Student",
new XAttribute("Id","1"),
new XElement("Name","darren")
))
);
doc.Save(path);
return Json(new {msg = true}, JsonRequestBehavior.AllowGet);
}
在Index.cshtml中通過(guò)異步請(qǐng)求:
@model IEnumerable<MvcApplication1.Models.Student>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<input type="button" value="創(chuàng)建XML" id="create"/>
@section scripts
{
<script type="text/javascript">
$(function() {
$('#create').on('click', function() {
$.ajax({
url: '@Url.Action("AddXml", "Home")',
dataType: 'json',
data: {},
type: 'POST',
success: function(data) {
if (data.msg) {
alert('創(chuàng)建成功');
}
}
});
});
});
</script>
}
顯示XML文件元素
修改HomeController中的Index方法為:
public ActionResult Index()
{
string path = Server.MapPath("~/new.xml");
List<Student> result = new List<Student>();
var nodes = ReadXML(path).Descendants("Student");
foreach (var node in nodes)
{
Student student = new Student();
student.Id = Convert.ToInt32(node.Attribute("Id").Value);
foreach (var ele in node.Elements())
{
student.Name = ele.Value;
}
result.Add(student);
}
return View(result);
}
private XDocument ReadXML(string path)
{
XDocument xDoc = new XDocument();
xDoc = XDocument.Load(path);
return xDoc;
}
修改Home/Index.cshtml為:
@model IEnumerable<MvcApplication1.Models.Student>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<input type="button" value="創(chuàng)建XML" id="create"/>
<table>
<tr>
<th>編號(hào)</th>
<th>姓名</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@Html.ActionLink("修改","Update","Home",new {id= item.Id},null)</td>
<td>@Html.ActionLink("刪除","Delete","Home", new {id = item.Id},null)</td>
</tr>
}
</table>
<br/>
@Html.ActionLink("創(chuàng)建","Create","Home")
@section scripts
{
<script type="text/javascript">
$(function() {
$('#create').on('click', function() {
$.ajax({
url: '@Url.Action("AddXml", "Home")',
dataType: 'json',
data: {},
type: 'POST',
success: function(data) {
if (data.msg) {
alert('創(chuàng)建成功');
}
}
});
});
});
</script>
}
添加元素到XML文件中
HomeController中:
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Student student)
{
string path = Server.MapPath("~/new.xml");
XDocument xd = XDocument.Load(path);
XElement newStudent = new XElement("Student",
new XAttribute("Id", student.Id),
new XElement("Name",student.Name));
xd.Root.Add(newStudent);
xd.Save(path);
return RedirectToAction("Index");
}
Home/Create.csthml中:
@model MvcApplication1.Models.Student
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new {id = "addForm"}))
{
@Html.LabelFor(m => m.Id)
@Html.EditorFor(m => m.Id)
<br/>
@Html.LabelFor(m => m.Name)
@Html.EditorFor(m => m.Name)
<br/>
<input type="submit" value="創(chuàng)建"/>
}
修改XML文件中的元素
HomeController中:
public ActionResult Update(string id)
{
string path = Server.MapPath("~/new.xml");
XElement xe = XElement.Load(path);
var studentXe = xe.Elements("Student").Where(e => e.Attribute("Id").Value == id).FirstOrDefault();
Student student = new Student();
student.Id = Convert.ToInt32(studentXe.Attribute("Id").Value);
student.Name = studentXe.Element("Name").Value;
return View(student);
}
[HttpPost]
public ActionResult Update(Student student)
{
string path = Server.MapPath("~/new.xml");
var studentId = student.Id.ToString();
XDocument xd = XDocument.Load(path);
XElement node =
xd.Root.Elements("Student").Where(e => e.Attribute("Id").Value == studentId).FirstOrDefault();
node.SetElementValue("Name", student.Name);
xd.Save(path);
return RedirectToAction("Index");
}
Home/Update.csthml中:
@model MvcApplication1.Models.Student
@{
ViewBag.Title = "Update";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Update</h2>
@using (Html.BeginForm("Update", "Home", FormMethod.Post, new {id = "editForm"}))
{
@Html.HiddenFor(m => m.Id)
@Html.LabelFor(m => m.Name)
@Html.EditorFor(m => m.Name)
<br/>
<input type="submit" value="修改"/>
}
刪除XML文件中的元素
HomeController中:
public ActionResult Delete(string id)
{
string path = Server.MapPath("~/new.xml");
XElement xe = XElement.Load(path);
var studentXe = xe.Elements("Student").Where(e => e.Attribute("Id").Value == id).FirstOrDefault();
Student student = new Student();
student.Id = Convert.ToInt32(studentXe.Attribute("Id").Value);
student.Name = studentXe.Element("Name").Value;
return View(student);
}
[HttpPost]
public ActionResult Delete(Student student)
{
string path = Server.MapPath("~/new.xml");
var studentId = student.Id.ToString();
XDocument xd = XDocument.Load(path);
xd.Root.Elements("Student").Where(e => e.Attribute("Id").Value == studentId).Remove();
xd.Save(path);
return RedirectToAction("Index");
}
Home/Delete.cshtml中:
@model MvcApplication1.Models.Student
@{
ViewBag.Title = "Delete";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Delete</h2>
@Model.Id
<br/>
@Model.Name
<br/>
@using (Html.BeginForm("Delete", "Home", FormMethod.Post, new {id = "delForm"}))
{
@Html.HiddenFor(m => m.Id)
<input type="submit" value="刪除"/>
}
原文鏈接:https://www.cnblogs.com/darrenji/p/3790250.html
相關(guān)推薦
- 2021-12-05 Go語(yǔ)言配置數(shù)據(jù)庫(kù)連接池的實(shí)現(xiàn)_Golang
- 2022-10-24 C語(yǔ)言詳解分析進(jìn)程控制中進(jìn)程終止的實(shí)現(xiàn)_C 語(yǔ)言
- 2022-07-29 Python列表append()函數(shù)使用方法詳解_python
- 2023-07-09 echarts的series已經(jīng)為空但是還加載出數(shù)據(jù)
- 2022-12-12 flutter?InheritedWidget使用方法總結(jié)_Android
- 2022-11-14 C++11新特性之右值引用與完美轉(zhuǎn)發(fā)詳解_C 語(yǔ)言
- 2022-09-06 Redis數(shù)據(jù)結(jié)構(gòu)SortedSet的底層原理解析_Redis
- 2023-07-10 Django進(jìn)行docker服務(wù)器部署
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支