C#操作XML

读取:

引用命名空间:using System.Xml; 

XmlDocument xdoc = new XmlDocument(); //创建xml模型对象

XmlReaderSettings settings = new XmlReaderSettings(); //创建xml功能对象
settings.IgnoreComments = true;//忽略文档里面的注释

//创建xml读取对象,参数1:映射的xml文件绝对路径,参数2:xml功能对象
XmlReader reader = XmlReader.Create(Server.MapPath("xmlFile/bookData.xml"), settings);

xdoc.Load(reader); //加载xml读取对象,将xml内容读取到 xml模型对象 中
            
XmlNode xnode = xdoc.SelectSingleNode("main"); //查找匹配的第一个节点

XmlNodeList nlist = xnode.ChildNodes; //获取找到的节点中所有的子节点

List<Book> blist = new List<Book>(); //实体模型集合

foreach (XmlNode xn in nlist) //遍历所有的子节点
{
    Book b = new Book();

    XmlElement xe = xn as XmlElement; //转换为xml节点元素

    b.BookType = xe.GetAttribute("type"); //获取属性值
    b.BookIds = xe.GetAttribute("ids");

    XmlNodeList xnlist = xe.ChildNodes; //获取节点元素中的子级元素
    b.BookTitle = xnlist[0].InnerText;  //获取元素内容
    b.BookAuthor = xnlist[1].InnerText;
    b.BookPrice = Convert.ToDecimal(xnlist[2].InnerText);

    blist.Add(b);
}

reader.Close(); //!!! 使用完毕后一定要关闭读取

XML文件格式:

<?xml version="1.0" encoding="utf-8"?>

<main>
  <!--必修课-->
  <book type="必修课" ids="1-101">
    <title>语文</title>
    <author>张三</author>
    <price>30.00</price>
  </book>
  <book type="必修课" ids="1-102">
    <title>数学</title>
    <author>李四</author>
    <price>40.00</price>
  </book>
  <book type="必修课" ids="1-103">
    <title>英语</title>
    <author>王五</author>
    <price>50.00</price>
  </book>
  <!--选修课-->
  <book type="选修课" ids="2-201">
    <title>计算机</title>
    <author>赵六</author>
    <price>110.00</price>
  </book>
  <book type="选修课" ids="2-202">
    <title>美术素描</title>
    <author>陈奇</author>
    <price>90.00</price>
  </book>
</main>

实体模型:

    public class Book
    {
        public string BookType { get; set; }
        public string BookIds { get; set; }
        public string BookTitle { get; set; }
        public string BookAuthor { get; set; }
        public decimal BookPrice { get; set; }
    }







  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值