tnblog
首页
视频
资源
登录

XML文件的读写

5005人阅读 2019/11/28 16:17 总访问:91885 评论:0 收藏:0 手机
分类: .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>


效果如下:


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

评价
网络上你重拳出击,现实中你刚上初一
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术