分类:
.NET MVC
各位童鞋们,今天我们一起来学习一下XML文件的读取
XML用途:配置、传输、储存。
引入命名口空间:using System.Xml.Linq;
话不多说,咱们直接上代码:
public ActionResult Index()
{
//根节点
XElement parent = new XElement("father");
//子节点
XElement childrens = new XElement("childrens");
parent.Add(childrens);
Write(childrens, "c001", "张三", "阳光");
Write(childrens, "c002", "李白", "有文采");
parent.Save(Server.MapPath("~/Xmls/parent.xml"));
return View();
}
//写XMl文件
public ActionResult Write(XElement xml, string cNo, string xmlName, string xmlDesc)
{
XElement children = new XElement("children");
children.SetAttributeValue("cNo", cNo);
xml.Add(children);
children.Add(new XElement("childrenName", xmlName));
children.Add(new XElement("childrenDesc", xmlDesc));
return View();
}Xml文件如下图:

然后我们接下来写一个读取的方法
public ActionResult Read()
{
//加载Xml文件
XElement xml = XElement.Load(Server.MapPath("~/Xmls/parent.xml"));
List<string> Names = new List<string>();
foreach (XElement item in xml.Element("childrens").Elements("children"))
{
Names.Add(item.Element("childrenName").Value);
}
return View(Names);
}前台页面解析数据:
@model List<string>
<div>
@foreach (var item in Model)
{
<a href="javascript:;">@item</a>
}
</div>效果如下:

这样我们就可以读取到刚才我们添加的数据了,各位童鞋可以根据自己的需要来修改!
评价
