C# - Xml的操作

 Xml
 Xml文件【library.xml】
<?xml version="1.0" encoding="utf-8" ?>
<!-- 图书馆 -->
<library Name="北京首都图书馆">
  <bookstore>
    <!--记录书本的信息-->
    <book Type="必修课" ISBN="7-111-19149-2">
      <title>数据结构</title>
      <author>严蔚敏</author>
      <price>30.00</price>
    </book>
    <book Type="必修课" ISBN="7-111-19149-3">
      <title>路由型与交换型互联网基础</title>
      <author>程庆梅</author>
      <price>27.00</price>
    </book>
    <book Type="必修课" ISBN="7-111-19149-4">
      <title>计算机硬件技术基础</title>
      <author>李继灿</author>
      <price>25.00</price>
    </book>
    <book Type="必修课" ISBN="7-111-19149-5">
      <title>软件质量保证与管理</title>
      <author>朱少民</author>
      <price>39.00</price>
    </book>
    <book Type="必修课" ISBN="7-111-19149-6">
      <title>算法设计与分析</title>
      <author>王红梅</author>
      <price>23.00</price>
    </book>
    <book Type="选修课" ISBN="7-111-19149-1">
      <title>计算机操作系统</title>
      <author>7-111-19149-1</author>
      <price>28</price>
    </book>
  </bookstore>
</library>
 实体类【BookInfo.cs】
namespace XmlStudy.Model
{
    public class BookInfo
    {
        /// <summary>
        /// 所对应的课程类型
        /// </summary>
        public string BookType { get; set; }

        /// <summary>
        /// 书所对应的ISBN号
        /// </summary>
        public string BookISBN { get; set; }

        /// <summary>
        /// 书名
        /// </summary>
        public string BookName { get; set; }

        /// <summary>
        /// 作者
        /// </summary>
        public string BookAuthor { get; set; }

        /// <summary>
        /// 价格
        /// </summary>
        public double BookPrice { get; set; }
    }
}
 XmlDocument 

   使用XmlDocument是一种基于文档结构模型的方式来读取XML文件.在XML文件中,我们可以把XML看作是由文档声明(Declare),元素(Element),属性(Attribute),文本(Text)等构成的一个树.最开始的一个结点叫作根结点,每个结点都可以有自己的子结点.得到一个结点后,可以通过一系列属性或方法得到这个结点的值或其它的一些属性.例如:

xn 代表一个结点
xn.Name;//这个结点的名称
xn.Value;//这个结点的值
xn.ChildNodes;//这个结点的所有子结点
xn.ParentNode;//这个结点的父结点

 整体案例:

using Newtonsoft.Json;
using System;
using System.IO;
using System.Xml;
using XmlStudy.Model;

namespace XmlStudy
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlReaderSettings settings = new XmlReaderSettings
            {
                IgnoreComments = true//忽略文档里面的注释
            };
            string path = Directory.GetCurrentDirectory();
            XmlReader xmlReader = XmlReader.Create(path + "\\XmlFile\\library.xml", settings);
            xmlDoc.Load(xmlReader);
            xmlReader.Close();

            //得到根节点
            XmlNode libraryNode = xmlDoc.SelectSingleNode("library");//参数区分大小写,没有此节点时返回null

            //获取属性值
            XmlElement libraryElement = (XmlElement)libraryNode;
            Console.WriteLine(libraryElement.GetAttribute("Name"));//参数区分大小写,没有此节点时返回null

            //得到bookstore节点
            XmlNode bookStoreNode = xmlDoc.SelectSingleNode("/library/bookstore");
            XmlNodeList bookNodeList = bookStoreNode.ChildNodes;
            foreach (XmlNode bookNode in bookNodeList)
            {
                BookInfo bookInfo = new BookInfo();

                XmlElement bookElement = (XmlElement)bookNode;
                bookInfo.BookType = bookElement.GetAttribute("Type");
                bookInfo.BookISBN = bookElement.GetAttribute("ISBN");

                bookInfo.BookName = bookNode.SelectSingleNode("title").InnerText;//没有此节点,InnerText属性会异常
                bookInfo.BookAuthor = bookNode.SelectSingleNode("author").InnerText;
                bookInfo.BookPrice = Convert.ToDouble(bookNode.SelectSingleNode("price").InnerText);

                Console.WriteLine(JsonConvert.SerializeObject(bookInfo));
            }


            //新加一个节点
            XmlElement newBookNode = xmlDoc.CreateElement("book");

            //设置节点属性
            XmlAttribute newType = xmlDoc.CreateAttribute("Type");
            newType.InnerText = "新加类型";
            newBookNode.SetAttributeNode(newType);

            //添加子节点
            XmlElement titleElement = xmlDoc.CreateElement("title");
            titleElement.InnerText = "新加书籍";
            newBookNode.AppendChild(titleElement);

            bookStoreNode.AppendChild(newBookNode);
            xmlDoc.Save(path + "\\XmlFile\\library.xml");


            //删除一个节点
            string strPath = string.Format("/library/bookstore/book[@ISBN=\"{0}\"]", "7-111-19149-4");
            XmlElement selectDeleteXe = (XmlElement)xmlDoc.SelectSingleNode(strPath);  //SelectSingleNode 根据XPath表达式,获得符合条件的第一个节点.
            selectDeleteXe.ParentNode.RemoveChild(selectDeleteXe);
            xmlDoc.Save(path + "\\XmlFile\\library.xml");

            //修改数据
            strPath = string.Format("/library/bookstore/book[@ISBN=\"{0}\"]", "7-111-19149-3");
            XmlElement selectUpdateXe = (XmlElement)xmlDoc.SelectSingleNode(strPath);
            selectUpdateXe.SetAttribute("Type", "修改");//也可以通过SetAttribute来增加一个属性
            selectUpdateXe.GetElementsByTagName("title").Item(0).InnerText = "修改标题";
            selectUpdateXe.GetElementsByTagName("author").Item(0).InnerText = "修改作者";
            selectUpdateXe.GetElementsByTagName("price").Item(0).InnerText = "100.0";
            xmlDoc.Save(path + "\\XmlFile\\library.xml");
        }
    }
}
 使用XmlDocument - Read / Write / Delete / Update
 加载xml文件
XmlDocument xmlDoc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings
{
    IgnoreComments = true//忽略文档里面的注释
};
string path = Directory.GetCurrentDirectory();
XmlReader xmlReader = XmlReader.Create(path + "\\XmlFile\\library.xml", settings);
xmlDoc.Load(xmlReader);
xmlReader.Close();
 加载xml字符串
string plan = @"Xml字符串";
XmlDocument xml = new XmlDocument();
xml.LoadXml(plan);
 读取【特别注意,特殊的xml比如:<MSG xmlns="http://www.travelsky.com/2006/dcsi"> 这个xmlns=会导致获取不到这个节点的值,可以将其替换为xmlns1=】
//得到根节点
XmlNode libraryNode = xmlDoc.SelectSingleNode("library");//参数区分大小写,没有此节点时返回null

//获取属性值
XmlElement libraryElement = (XmlElement)libraryNode;
Console.WriteLine(libraryElement.GetAttribute("Name"));//参数区分大小写,没有此节点时返回null

//得到bookstore节点
XmlNode bookStoreNode = xmlDoc.SelectSingleNode("/library/bookstore");
XmlNodeList bookNodeList = bookStoreNode.ChildNodes;
foreach (XmlNode bookNode in bookNodeList)
{
    BookInfo bookInfo = new BookInfo();

    XmlElement bookElement = (XmlElement)bookNode;
    bookInfo.BookType = bookElement.GetAttribute("Type");
    bookInfo.BookISBN = bookElement.GetAttribute("ISBN");

    bookInfo.BookName = bookNode.SelectSingleNode("title").InnerText;//没有此节点,InnerText属性会异常
    bookInfo.BookAuthor = bookNode.SelectSingleNode("author").InnerText;
    bookInfo.BookPrice = Convert.ToDouble(bookNode.SelectSingleNode("price").InnerText);

    Console.WriteLine(JsonConvert.SerializeObject(bookInfo));
}
 添加
//新加一个节点
XmlElement newBookNode = xmlDoc.CreateElement("book");

//设置节点属性
XmlAttribute newType = xmlDoc.CreateAttribute("Type");
newType.InnerText = "新加类型";
newBookNode.SetAttributeNode(newType);

//添加子节点
XmlElement titleElement = xmlDoc.CreateElement("title");
titleElement.InnerText = "新加书籍";
newBookNode.AppendChild(titleElement);

bookStoreNode.AppendChild(newBookNode);
xmlDoc.Save(path + "\\XmlFile\\library.xml");
 修改
//修改数据
strPath = string.Format("/library/bookstore/book[@ISBN=\"{0}\"]", "7-111-19149-3");
XmlElement selectUpdateXe = (XmlElement)xmlDoc.SelectSingleNode(strPath);
selectUpdateXe.SetAttribute("Type", "修改");//也可以通过SetAttribute来增加一个属性
selectUpdateXe.GetElementsByTagName("title").Item(0).InnerText = "修改标题";
selectUpdateXe.GetElementsByTagName("author").Item(0).InnerText = "修改作者";
selectUpdateXe.GetElementsByTagName("price").Item(0).InnerText = "100.0";
xmlDoc.Save(path + "\\XmlFile\\library.xml");
 删除
//删除一个节点
string strPath = string.Format("/library/bookstore/book[@ISBN=\"{0}\"]", "7-111-19149-4");
XmlElement selectDeleteXe = (XmlElement)xmlDoc.SelectSingleNode(strPath);  //SelectSingleNode 根据XPath表达式,获得符合条件的第一个节点.
selectDeleteXe.ParentNode.RemoveChild(selectDeleteXe);
xmlDoc.Save(path + "\\XmlFile\\library.xml");
posted @ 2021-05-20 17:44  gygtech  Views(88)  Comments(0Edit  收藏  举报