www.weide1946.com:中常用的两种读取XML文件的方法

2019-05-07 10:10 来源:未知

如下XML文件:(算是三个属性值比较多的xml文件。。。读取该Xml算是笔者在集团其实的二个职责)

初稿地址:

<?xml version="1.0" encoding="UTF-8"?>
<serverset>
    <devset PrintNumber="1" ControlBarcode="" ControlEBarcode="" ControlPIX="" PrinterPort="0" isShowAreaName="0" PrinterPortData="127.0.0.1" SparePrinterNumber="1" SparePrinterNumber2="1" ProductionAreaName="1" PrintType="QT;1B;1K;1L;1M;" PrintDevType="0" logicalDpiW="" logicalDpiH="" Baudrate="4800" QZHEIGHT="1" QZwaittime="45" FILEwaittime="45" enablestwoway="1" CommandType="0"/>
    <devset PrintNumber="2" ControlBarcode="" ControlEBarcode="" ControlPIX="" PrinterPort="0" isShowAreaName="0" PrinterPortData="127.0.0.211" SparePrinterNumber="1" SparePrinterNumber2="1" ProductionAreaName="" PrintType="" PrintDevType="0" logicalDpiW="" logicalDpiH="" Baudrate="4800" QZHEIGHT="1" QZwaittime="45" FILEwaittime="45" enablestwoway="0" CommandType="0"/>
    <devset PrintNumber="3" ControlBarcode="" ControlEBarcode="" ControlPIX="" PrinterPort="0" isShowAreaName="0" PrinterPortData="127.0.0.3" SparePrinterNumber="1" SparePrinterNumber2="1" ProductionAreaName="" PrintType="" PrintDevType="0" logicalDpiW="" logicalDpiH="" Baudrate="4800" QZHEIGHT="1" QZwaittime="45" FILEwaittime="45" enablestwoway="0" CommandType="0"/>
    <devset PrintNumber="4" ControlBarcode="" ControlEBarcode="" ControlPIX="" PrinterPort="3" isShowAreaName="0" PrinterPortData="USB2" SparePrinterNumber="1" SparePrinterNumber2="1" ProductionAreaName="" PrintType="" PrintDevType="2" logicalDpiW="" logicalDpiH="" Baudrate="4800" QZHEIGHT="1" QZwaittime="45" FILEwaittime="45" enablestwoway="1" CommandType="0"/>
    <OrtherInfo printMode="1" PrintTimeConfig="5" FilterEmptyRows="0" PrintFilePath="D:/choice/ftp/tiktenPrint" BackFilePath="D:/choice/ftp/prnBakDir" readBOHPrintConfig="1" CondingFormat="0" isShowChangeBill="0" isRunUpgrade="0" SingleTurnSpaceTime="30" storeprnPath="127.0.0.1" FtpPort="" BCode="1020001" UploadVersionAddress="" UploadVersionPort="0"/>
</serverset>

版权证明:本文为博主原创小说,未经博主允许不得转发。

始建2个类WriteXml用来封装读取Xml的和属性值方法:代码如下

 XML文件是1种常用的文件格式,举例WinForm里面的app.config以及Web程序中的web.config文件,还有许多首要的场子都有它的身材。Xml是Internet环境中跨平台的,依赖于剧情的本领,是当下拍卖结构化文书档案消息的庞大工具。XML是1种简易的多寡存款和储蓄语言,使用壹多级简单的符号描述数据,而那些标识能够用方便的措施确立,即使XML占用的长空比二进制数据要侵吞更加多的半空中,但XML极其简约轻便了然和动用。微软也提供了1密密麻麻类库来倒协助大家在应用程序中存款和储蓄XML文件。

class ReadXml
    {
        /// <summary>
        /// 第一根节点的属性
        /// </summary>
        public string PrintNumber { get; set; }
        public string ControlBarcode { get; set; }
        public string ControlEBarcode { get; set; }
        public string ControlPIX { get; set; }
        public string PrinterPort { get; set; }
        public string isShowAreaName { get; set; }
        public string PrinterPortData { get; set; }
        public string SparePrinterNumber { get; set; }
        public string SparePrinterNumber2 { get; set; }
        public string ProductionAreaName { get; set; }
        public string PrintType { get; set; }
        public string PrintDevType { get; set; }
        public string logicalDpiW { get; set; }
        public string logicalDpiH { get; set; }
        public string Baudrate { get; set; }
        public string QZHEIGHT { get; set; }
        public string QZwaittime { get; set; }
        public string FILEwaittime { get; set; }
        public string enablestwoway { get; set; }
        public string CommandType { get; set; }

        /// <summary>
        /// 第二根节点的属性
        /// </summary>

        public string printMode { get; set; }
        public string PrintTimeConfig { get; set; }
        public string FilterEmptyRows { get; set; }
        public string PrintFilePath { get; set; }
        public string BackFilePath { get; set; }
        public string readBOHPrintConfig { get; set; }
        public string CondingFormat { get; set; }
        public string isShowChangeBill { get; set; }
        public string isRunUpgrade { get; set; }
        public string SingleTurnSpaceTime { get; set; }
        public string storeprnPath { get; set; }
        public string FtpPort { get; set; }
        public string BCode { get; set; }
        public string UploadVersionAddress { get; set; }
        public string UploadVersionPort { get; set; }

        public void read()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(@"D:ChoicPrintConfig.xml");//读取xml文件
            XmlNode xn = xmlDoc.SelectSingleNode("serverset");
            XmlNodeList xnlNL = xn.SelectNodes("devset");//得到根节点
            foreach (XmlNode xnl in xnlNL)//遍历devset
            {
                WriteAndRead wr = new WriteAndRead();
                XmlElement xe = (XmlElement)xnl;
                wr.PrintNumber = xe.GetAttribute("PrintNumber").ToString();
                wr.ControlBarcode = xe.GetAttribute("ControlBarcode").ToString();
                wr.ControlEBarcode = xe.GetAttribute("ControlEBarcode").ToString();
                wr.ControlPIX = xe.GetAttribute("ControlPIX").ToString();
                wr.PrinterPort = xe.GetAttribute("PrinterPort").ToString();
                wr.isShowAreaName = xe.GetAttribute("isShowAreaName").ToString();
                wr.PrinterPortData = xe.GetAttribute("PrinterPortData").ToString();
                wr.SparePrinterNumber = xe.GetAttribute("SparePrinterNumber").ToString();
                wr.SparePrinterNumber2 = xe.GetAttribute("SparePrinterNumber2").ToString();
                wr.ProductionAreaName = xe.GetAttribute("ProductionAreaName").ToString();
                wr.PrintType = xe.GetAttribute("PrintType").ToString();
                wr.PrintDevType = xe.GetAttribute("PrintDevType").ToString();
                wr.logicalDpiW = xe.GetAttribute("logicalDpiW").ToString();
                wr.logicalDpiH = xe.GetAttribute("logicalDpiH").ToString();
                wr.Baudrate = xe.GetAttribute("Baudrate").ToString();
                wr.QZHEIGHT = xe.GetAttribute("QZHEIGHT").ToString();
                wr.QZwaittime = xe.GetAttribute("QZwaittime").ToString();
                wr.FILEwaittime = xe.GetAttribute("FILEwaittime").ToString();
                wr.enablestwoway = xe.GetAttribute("enablestwoway").ToString();
                wr.CommandType = xe.GetAttribute("CommandType").ToString();

                Console.WriteLine("PrintNumber:"   wr.PrintNumber   "tControlBarcode:"   wr.ControlBarcode   "tControlEBarcode:"   wr.ControlEBarcode
                     "tControlPIX:"   wr.ControlPIX   "tPrinterPort:"   wr.PrinterPort   "tisShowAreaName:"   wr.isShowAreaName   "tPrinterPortData:"
                     wr.PrinterPortData   "tSparePrinterNumber:"   wr.SparePrinterNumber   "tSparePrinterNumber2:"   wr.SparePrinterNumber2
                     "tProductionAreaName:"   wr.ProductionAreaName   "tPrintType:"   wr.PrintType   "tPrintDevType:"   wr.PrintDevType   "tlogicalDpiW:"
                     wr.logicalDpiW   "tlogicalDpiH:"   wr.logicalDpiH   "tBaudrate:"   wr.Baudrate   "tQZHEIGHT:"   wr.QZHEIGHT   "tQZwaittime:"   wr.QZwaittime
                     "tFILEwaittime:"   wr.FILEwaittime   "tenablestwoway:"   wr.enablestwoway   "tCommandType:"   wr.CommandType);
                Console.WriteLine();

            }

            XmlNodeList xnlNL1 = xn.SelectNodes("OrtherInfo");//得到第二个根节点
            foreach (XmlNode xnl in xnlNL1)//OrtherInfo
            {

                WriteAndRead wr = new WriteAndRead();
                XmlElement xe = (XmlElement)xnl;
                wr.printMode = xe.GetAttribute("printMode").ToString();
                wr.PrintTimeConfig = xe.GetAttribute("PrintTimeConfig").ToString();
                wr.FilterEmptyRows = xe.GetAttribute("FilterEmptyRows").ToString();
                wr.PrintFilePath = xe.GetAttribute("PrintFilePath").ToString();
                wr.BackFilePath = xe.GetAttribute("BackFilePath").ToString();
                wr.readBOHPrintConfig = xe.GetAttribute("readBOHPrintConfig").ToString();
                wr.CondingFormat = xe.GetAttribute("CondingFormat").ToString();
                wr.isShowChangeBill = xe.GetAttribute("isShowChangeBill").ToString();
                wr.isRunUpgrade = xe.GetAttribute("isRunUpgrade").ToString();
                wr.SingleTurnSpaceTime = xe.GetAttribute("SingleTurnSpaceTime").ToString();
                wr.storeprnPath = xe.GetAttribute("storeprnPath").ToString();
                wr.FtpPort = xe.GetAttribute("FtpPort").ToString();
                wr.UploadVersionAddress = xe.GetAttribute("UploadVersionAddress").ToString();
                wr.UploadVersionPort = xe.GetAttribute("UploadVersionPort").ToString();
                Console.WriteLine("printMode:"   wr.printMode   "tPrintTimeConfig:"   wr.PrintTimeConfig   "tFilterEmptyRows:"   wr.FilterEmptyRows
                      "tPrintFilePath:"   wr.PrintFilePath   "tBackFilePath:"   wr.BackFilePath   "treadBOHPrintConfig:"   wr.readBOHPrintConfig
                      "tCondingFormat:"   wr.CondingFormat   "tisShowChangeBill:"   wr.isShowChangeBill   "tisRunUpgrade:"   wr.isRunUpgrade   "tSingleTurnSpaceTime:"  
                    wr.SingleTurnSpaceTime   "tstoreprnPath:"   wr.storeprnPath   "tFtpPort:"   wr.FtpPort   "tUploadVersionAddress:"   wr.UploadVersionAddress   "tUploadVersionPort:"   wr.UploadVersionPort);
            }    
        }

“在程序中访问进而操作XML文件一般有三种模型,分别是选拔DOM(文书档案对象模型)和流模型,使用DOM的补益在于它同意编辑和翻新XML文书档案,可以随意访问文书档案中的数据,可以动用X帕特h查询,可是,DOM的瑕疵在于它要求贰遍性的加载整个文书档案到内存中,对于大型的文书档案,那会招致能源难题。流模型很好的化解了那一个难题,因为它对XML文件的访问采取的是流的概念,也正是说,任哪一天候在内部存款和储蓄器中唯有当前节点,但它也有它的阙如,它是只读的,仅向前的,不能够在文书档案中试行向后导航操作。”具体参见在Visual C#中选择XML指南之读取XML

在调整台上运转。。

上边小编将介绍两种常用的读取XML文件的方法。分别是

 class Program
    {
        static void Main(string[] args)
        {
           ReadXml RX = new ReadeXml();
            RX.Read();
            Console.Read();
        }
    }
   1: 使用 XmlDocument

   2: 使用 XmlTextReader

   3: 使用 Linq to Xml

运维结果如下:

此处我先创立3个XML文件,名称叫Book.xml上边全数的章程都以基于这么些XML文件的,文件内容如下:

www.weide1946.com 1

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

   2: <bookstore>

   3:   <!--记录书本的信息-->

   4:   <book Type="必修课" ISBN="7-111-19149-2">

   5:     <title>数据结构</title>

   6:     <author>严蔚敏</author>

   7:     <price>30.00</price>

   8:   </book>

   9:   <book Type="必修课" ISBN="7-111-19149-3">

  10:     <title>路由型与交换型互联网基础</title>

  11:     <author>程庆梅</author>

  12:     <price>27.00</price>

  13:   </book>

  14:   <book Type="必修课" ISBN="7-111-19149-4">

  15:     <title>计算机硬件技术基础</title>

  16:     <author>李继灿</author>

  17:     <price>25.00</price>

  18:   </book>

  19:   <book Type="必修课" ISBN="7-111-19149-5">

  20:     <title>软件质量保证与管理</title>

  21:     <author>朱少民</author>

  22:     <price>39.00</price>

  23:   </book>

  24:   <book Type="必修课" ISBN="7-111-19149-6">

  25:     <title>算法设计与分析</title>

  26:     <author>王红梅</author>

  27:     <price>23.00</price>

  28:   </book>

  29:   <book Type="选修课" ISBN="7-111-19149-1">

  30:     <title>计算机操作系统</title>

  31:     <author>7-111-19149-1</author>

  32:     <price>28</price>

  33:   </book>

  34: </bookstore>

好了,以上正是读取该XML文件以及实际运作结果图。。。。。。。

为了便于读取,我还定义七个书的实体类,名叫BookModel,具体内容如下:

大咖们就当看个笑话啦!当然有哪个地方不对的地方或然能够改良的格局可以提出来。。。。对于一些没用读取过XML文件的程序员们。。可供参照他事他说加以考察

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:  

   6: namespace 使用XmlDocument

   7: {

   8:     public class BookModel

   9:     {

  10:         public BookModel()

  11:         { }

  12:         /// <summary>

  13:         /// 所对应的课程类型

  14:         /// </summary>

  15:         private string bookType;

  16:  

  17:         public string BookType

  18:         {

  19:             get { return bookType; }

  20:             set { bookType = value; }

  21:         }

  22:  

  23:         /// <summary>

  24:         /// 书所对应的ISBN号

  25:         /// </summary>

  26:         private string bookISBN;

  27:  

  28:         public string BookISBN

  29:         {

  30:             get { return bookISBN; }

  31:             set { bookISBN = value; }

  32:         }

  33:  

  34:         /// <summary>

  35:         /// 书名

  36:         /// </summary>

  37:         private string bookName;

  38:  

  39:         public string BookName

  40:         {

  41:             get { return bookName; }

  42:             set { bookName = value; }

  43:         }

  44:  

  45:         /// <summary>

  46:         /// 作者

  47:         /// </summary>

  48:         private string bookAuthor;

  49:  

  50:         public string BookAuthor

  51:         {

  52:             get { return bookAuthor; }

  53:             set { bookAuthor = value; }

  54:         }

  55:  

  56:         /// <summary>

  57:         /// 价格

  58:         /// </summary>

  59:         private double bookPrice;

  60:  

  61:         public double BookPrice

  62:         {

  63:             get { return bookPrice; }

  64:             set { bookPrice = value; }

  65:         }

  66:     }

  67: }

  

1.使用XmlDocument.

运用XmlDocument是1种基于文书档案结构模型的措施来读取XML文件.在XML文件中,大家能够把XML看作是由文书档案注解(Declare),成分(Element),属性(Attribute),文本(Text)等组合的三个树.最初阶的3个结点叫作根结点,每一种结点都得以有友好的子结点.得到二个结点后,能够透过壹多元属性或情势赢得这几个结点的值或其余的片段属性.举例:

   1: xn 代表一个结点

   2: xn.Name;//这个结点的名称

   3: xn.Value;//这个结点的值

   4: xn.ChildNodes;//这个结点的所有子结点

   5: xn.ParentNode;//这个结点的父结点

   6: .......

1.一 读取全部的数据.

利用的时候,首先声美素佳儿个XmlDocument对象,然后调用Load方法,从钦命的门道加载XML文件.

   1: XmlDocument doc = new XmlDocument();

   2: doc.Load(@"....Book.xml");

然后能够由此调用SelectSingleNode获得钦定的结点,通过GetAttribute得到切实的天性值.参看上边包车型大巴代码

   1: // 得到根节点bookstore

   2: XmlNode xn = xmlDoc.SelectSingleNode("bookstore");

   3:  

   4:  

   5: // 得到根节点的所有子节点

   6: XmlNodeList xnl = xn.ChildNodes;

   7:  

   8: foreach (XmlNode xn1 in xnl)

   9: {

  10:     BookModel bookModel = new BookModel();

  11:     // 将节点转换为元素,便于得到节点的属性值

  12:     XmlElement xe = (XmlElement)xn1;

  13:     // 得到Type和ISBN两个属性的属性值

  14:     bookModel.BookISBN = xe.GetAttribute("ISBN").ToString();

  15:     bookModel.BookType = xe.GetAttribute("Type").ToString();

  16:     // 得到Book节点的所有子节点

  17:     XmlNodeList xnl0 = xe.ChildNodes;

  18:     bookModel.BookName=xnl0.Item(0).InnerText;

  19:     bookModel.BookAuthor=xnl0.Item(1).InnerText;

  20:     bookModel.BookPrice=Convert.ToDouble(xnl0.Item(2).InnerText);

  21:     bookModeList.Add(bookModel);

  22: }

  23: dgvBookInfo.DataSource = bookModeList;

在例行状态下,上面的代码好像未有怎么问题,可是对于读取上面的XML文件,则会出错,原因就是因为小编上边的XML文件之中有注释,我们可以参见Book.xml文件中的第二行,作者随意加的一句注释.注释也是一种结点类型,在未有特地表达的意况下,会默许它也是三个结点(Node).所以在把结点转变到成分的时候就能够报错."不大概将品种为“System.Xml.XmlComment”的靶子强制转变为项目“System.Xml.XmlElement”。"

www.weide1946.com 2

多亏它在这之中自带了消除办法,那即是在读取的时候,告诉编写翻译器让它忽略掉在这之中的笺注新闻.修改如下:

   1: XmlDocument xmlDoc = new XmlDocument();

   2: XmlReaderSettings settings = new XmlReaderSettings();

   3: settings.IgnoreComments = true;//忽略文档里面的注释

   4: XmlReader reader = XmlReader.Create(@"....Book.xml", settings);

   5: xmlDoc.Load(reader);

末段读取实现后,记得要关掉reader.

   1: reader.Close();

如此它就不会现出错误.

最终运转结果如下:

www.weide1946.com 3

一.二 扩充1本书的音信.

向文件中加多新的多少的时候,首先也是透过XmlDocument加载整个文书档案,然后经过调用SelectSingleNode方法赢得根结点,通过CreateElement方法创设成分,用CreateAttribute创设属性,用AppendChild把最近结点挂接在其它结点上,用SetAttributeNode设置结点的属性.具体代码如下:

加载文件并选出要结点:

   1: XmlDocument doc = new XmlDocument();

   2: doc.Load(@"....Book.xml");

   3: XmlNode root = doc.SelectSingleNode("bookstore");

始建一个结点,并设置结点的性质:

   1: XmlElement xelKey = doc.CreateElement("book");

   2: XmlAttribute xelType = doc.CreateAttribute("Type");

   3: xelType.InnerText = "adfdsf";

   4: xelKey.SetAttributeNode(xelType);

创建子结点:

   1: XmlElement xelAuthor = doc.CreateElement("author");

   2: xelAuthor.InnerText = "dfdsa";

   3: xelKey.AppendChild(xelAuthor);

最后把book结点挂接在要结点上,并保存整个文件:

   1: root.AppendChild(xelKey);

   2: doc.Save(@"....Book.xml");

用地方的主意,是向已部分文件上增添数据,纵然想覆盖原有的保有数据,能够改动一下,使用LoadXml方法:

   1: XmlDocument doc = new XmlDocument();

   2: doc.LoadXml("<bookstore></bookstore>");//用这句话,会把以前的数据全部覆盖掉,只有你增加的数据

一直把根结点采收取来了,前边不用SelectSingleNode方法选择根结点,直接成立结点就能够,代码同上.

一.叁 删除某三个数额

想要删除某一个结点,直接找到其父结点,然后调用RemoveChild方法就能够,未来器重的难点是什么找到那一个结点,上边的SelectSingleNode能够流传一个Xpath表,大家由此书的ISBN号来找到那本书所在的结点.如下:

   1: XmlElement xe = xmlDoc.DocumentElement; // DocumentElement 获取xml文档对象的根XmlElement.

   2: string strPath = string.Format("/bookstore/book[@ISBN="{0}"]", dgvBookInfo.CurrentRow.Cells[1].Value.ToString());

   3: XmlElement selectXe = (XmlElement)xe.SelectSingleNode(strPath);  //selectSingleNode 根据XPath表达式,获得符合条件的第一个节点.

   4: selectXe.ParentNode.RemoveChild(selectXe);

"/bookstore/book[@ISBN="{0}"]"是贰个Xpath表达式,找到ISBN号为所选那1行ISBN号的那本书,有关Xpath的学问请参谋:XPath 语法

一.4 修改某要条数据

修改某 条数据来讲,首先也是用Xpath表达式找到所需求修改的那多少个结点,然后一旦是因素的话,就直接对那么些因素赋值,倘若是性质的话,就用SetAttribute方法设置就能够.如下:

   1: XmlElement xe = xmlDoc.DocumentElement; // DocumentElement 获取xml文档对象的根XmlElement.

   2: string strPath = string.Format("/bookstore/book[@ISBN="{0}"]", dgvBookInfo.CurrentRow.Cells[1].Value.ToString());

   3: XmlElement selectXe = (XmlElement)xe.SelectSingleNode(strPath);  //selectSingleNode 根据XPath表达式,获得符合条件的第一个节点.

   4: selectXe.SetAttribute("Type", dgvBookInfo.CurrentRow.Cells[0].Value.ToString());//也可以通过SetAttribute来增加一个属性

   5: selectXe.GetElementsByTagName("title").Item(0).InnerText = dgvBookInfo.CurrentRow.Cells[2].Value.ToString();

   6: selectXe.GetElementsByTagName("author").Item(0).InnerText = dgvBookInfo.CurrentRow.Cells[3].Value.ToString();

   7: selectXe.GetElementsByTagName("price").Item(0).InnerText = dgvBookInfo.CurrentRow.Cells[4].Value.ToString();

   8: xmlDoc.Save(@"....Book.xml");

2.使用XmlTextReader和XmlTextWriter

XmlTextReader和XmlTextWriter是以流的花样来读写XML文件.

2.1XmlTextReader

动用XmlTextReader读取数据的时候,首先创制一个流,然后用read()方法来持续的向下读,根据读取的结点的门类来张开相应的操作.如下:

   1: XmlTextReader reader = new XmlTextReader(@"....Book.xml");

   2:            List<BookModel> modelList = new List<BookModel>();

   3:            BookModel model = new BookModel();

   4:            while (reader.Read())

   5:            {

   6:               

   7:                if (reader.NodeType == XmlNodeType.Element)

   8:                {

   9:                    if (reader.Name == "book")

  10:                    {

  11:                        model.BookType = reader.GetAttribute(0);

  12:                        model.BookISBN = reader.GetAttribute(1);

  13:                    }

  14:                    if (reader.Name == "title")

  15:                    {

  16:                        model.BookName=reader.ReadElementString().Trim();

  17:                    }

  18:                    if (reader.Name == "author")

  19:                    {

  20:                        model.BookAuthor = reader.ReadElementString().Trim();

  21:                    }

  22:                    if (reader.Name == "price")

  23:                    {

  24:                        model.BookPrice = Convert.ToDouble(reader.ReadElementString().Trim());

  25:                    }

  26:                }

  27:  

  28:                if (reader.NodeType == XmlNodeType.EndElement)

  29:                {

  30:                    modelList.Add(model);

  31:                    model = new BookModel();

  32:                }

  33:  

  34:                

  35:            }

  36:            modelList.RemoveAt(modelList.Count-1);

  37:            this.dgvBookInfo.DataSource = modelList;

重在是读取属性的时候,你要先知道哪1个结点拥有几天性格,然后通过GetAttribute方法来读取.读取属性还足以用其余1种格局,正是用MoveToAttribute方法.可参见下边包车型地铁代码:

   1: if (reader.Name == "book")

   2:     {

   3:         for (int i = 0; i < reader.AttributeCount; i  )

   4:         {

   5:             reader.MoveToAttribute(i);

   6:             string str = "属性:"   reader.Name   "="   reader.Value;

   7:         }

   8:         model.BookType = reader.GetAttribute(0);

   9:         model.BookISBN = reader.GetAttribute(1);

  10:     }

效益如下:

www.weide1946.com 4

2.2XmlTextWriter

XmlTextWriter写文件的时候,暗许是覆盖从前的文本,如若此文件名不设有,它将成立此文件.首先设置一下,你要创设的XML文件格式,

   1: XmlTextWriter myXmlTextWriter = new XmlTextWriter(@"....Book1.xml", null);

   2: //使用 Formatting 属性指定希望将 XML 设定为何种格式。 这样,子元素就可以通过使用 Indentation 和 IndentChar 属性来缩进。

   3: myXmlTextWriter.Formatting = Formatting.Indented;

接下来可以经过WriteStartElement和WriteElementString方法来成立成分,那贰者的分别正是1旦有子结点的因素,那么创设的时候就用WriteStartElement,然后去成立子成分,创造实现后,要调用相应的WriteEndElement来报告编写翻译器,创造实现,用WriteElementString来创立单个的因素,用WriteAttributeString来成立属性.如下:

   1: XmlTextWriter myXmlTextWriter = new XmlTextWriter(@"....Book1.xml", null);

   2:            //使用 Formatting 属性指定希望将 XML 设定为何种格式。 这样,子元素就可以通过使用 Indentation 和 IndentChar 属性来缩进。

   3:            myXmlTextWriter.Formatting = Formatting.Indented;

   4:  

   5:            myXmlTextWriter.WriteStartDocument(false);

   6:            myXmlTextWriter.WriteStartElement("bookstore");

   7:  

   8:            myXmlTextWriter.WriteComment("记录书本的信息");

   9:            myXmlTextWriter.WriteStartElement("book");

  10:  

  11:            myXmlTextWriter.WriteAttributeString("Type", "选修课");

  12:            myXmlTextWriter.WriteAttributeString("ISBN", "111111111");

  13:  

  14:            myXmlTextWriter.WriteElementString("author","张三");

  15:            myXmlTextWriter.WriteElementString("title", "职业生涯规划");

  16:            myXmlTextWriter.WriteElementString("price", "16.00");

  17:  

  18:            myXmlTextWriter.WriteEndElement();

  19:            myXmlTextWriter.WriteEndElement();

  20:  

  21:            myXmlTextWriter.Flush();

  22:            myXmlTextWriter.Close();

3.使用Linq to XML.

Linq是C#三.0中冒出的三个新特色,使用它能够方便的操作许繁多据源,也囊括XML文件.使用Linq操作XML文件充足的有益,而且也比较轻巧.上边直接看代码,

先定义 1个格局展现查询出来的数码

   1: private void showInfoByElements(IEnumerable<XElement> elements)

   2:        {

   3:            List<BookModel> modelList = new List<BookModel>();

   4:            foreach (var ele in elements)

   5:            {

   6:                BookModel model = new BookModel();

   7:                model.BookAuthor = ele.Element("author").Value;

   8:                model.BookName = ele.Element("title").Value;

   9:                model.BookPrice = Convert.ToDouble(ele.Element("price").Value);

  10:                model.BookISBN=ele.Attribute("ISBN").Value;

  11:                model.BookType=ele.Attribute("Type").Value;

  12:                

  13:                modelList.Add(model);

  14:            }

  15:            dgvBookInfo.DataSource = modelList;

  16:        }

叁.1读取全数的多少

平昔找到成分为book的那么些结点,然后遍历读取全体的结果.

   1: private void btnReadAll_Click(object sender, EventArgs e)

   2:        {

   3:            XElement xe = XElement.Load(@"....Book.xml");

   4:            IEnumerable<XElement> elements = from ele in xe.Elements("book")

   5:                                             select ele;

   6:            showInfoByElements(elements);

   7:        }

三.二插入一条数据

布置结点和性质都选拔new的主意,如下:

   1: private void btnInsert_Click(object sender, EventArgs e)

   2:         {

   3:             XElement xe = XElement.Load(@"....Book.xml");

   4:             XElement record = new XElement(

   5:             new XElement("book",

   6:             new XAttribute("Type", "选修课"),

   7:             new XAttribute("ISBN","7-111-19149-1"),

   8:             new XElement("title", "计算机操作系统"),

   9:             new XElement("author", "7-111-19149-1"),

  10:             new XElement("price", 28.00)));

  11:             xe.Add(record);

  12:             xe.Save(@"....Book.xml");

  13:             MessageBox.Show("插入成功!");

  14:             btnReadAll_Click(sender, e);

  15:         }

三.叁 删除选中的数量

首先得到中选的那一行,通过ISBN号来找到那个成分,然后用Remove方法直接删除,如下:

   1: private void btnDelete_Click(object sender, EventArgs e)

   2:        {

   3:            if (dgvBookInfo.CurrentRow != null)

   4:            {

   5:                //dgvBookInfo.CurrentRow.Cells[1]对应着ISBN号

   6:                string id = dgvBookInfo.CurrentRow.Cells[1].Value.ToString();

   7:                XElement xe = XElement.Load(@"....Book.xml");

   8:                IEnumerable<XElement> elements = from ele in xe.Elements("book")

   9:                                                 where (string)ele.Attribute("ISBN") == id

  10:                                                 select ele;

  12:                {

  11:                if (elements.Count() > 0)

  13:                    elements.First().Remove();

  14:                }

  15:                xe.Save(@"....Book.xml");

  16:                MessageBox.Show("删除成功!");

  17:                btnReadAll_Click(sender, e);

  18:  

  19:            }

  20:        }

叁.四 删除全体的数量

与地点的接近,选出全部的数码,然后用Remove方法,如下:

   1: private void btnDeleteAll_Click(object sender, EventArgs e)

   2:        {

   3:            XElement xe = XElement.Load(@"....Book.xml");

   4:            IEnumerable<XElement> elements = from ele in xe.Elements("book")

   5:                                             select ele;

   6:            if (elements.Count() > 0)

   7:            {

   8:                elements.Remove();

   9:            }

  10:            xe.Save(@"....Book.xml");

  11:            MessageBox.Show("删除成功!");

  12:            btnReadAll_Click(sender, e);

  13:        }

三.五 修改某一记录

率先猎取所要修改的某二个结点,然后用SetAttributeValue来修改属性,用ReplaceNodes来修改结点成分。如下:

   1: private void btnSave_Click(object sender, EventArgs e)

   2: {

   3:     XElement xe = XElement.Load(@"....Book.xml");

   4:     if (dgvBookInfo.CurrentRow != null)

   5:     {

   6:         //dgvBookInfo.CurrentRow.Cells[1]对应着ISBN号

   7:         string id = dgvBookInfo.CurrentRow.Cells[1].Value.ToString();

   8:         IEnumerable<XElement> element = from ele in xe.Elements("book")

   9:                                         where ele.Attribute("ISBN").Value == id

  10:                                         select ele;

  11:         if (element.Count() > 0)

  12:         {

  13:             XElement first = element.First();

  14:             ///设置新的属性

  15:             first.SetAttributeValue("Type", dgvBookInfo.CurrentRow.Cells[0].Value.ToString());

  16:             ///替换新的节点

  17:             first.ReplaceNodes(

  18:                      new XElement("title", dgvBookInfo.CurrentRow.Cells[2].Value.ToString()),  

  19:                      new XElement("author", dgvBookInfo.CurrentRow.Cells[3].Value.ToString()),

  20:                      new XElement("price", (double)dgvBookInfo.CurrentRow.Cells[4].Value) 

  21:                      );

  22:         }

  23:         xe.Save(@"....Book.xml");

  24:  

  25:         MessageBox.Show("修改成功!");

  26:         btnReadAll_Click(sender, e);

  27:     }

  28: }

终极效果如下:

www.weide1946.com 5

至于Linq to XML的文化咱们能够参见LINQ国人首创LINQ专著——《了解LINQ数据访问技艺》

版权声明:本文由韦德娱乐1946_韦德娱乐1946网页版|韦德国际1946官网发布于网络编程,转载请注明出处:www.weide1946.com:中常用的两种读取XML文件的方法