C # are three commonly used methods to read XML file

   Now I will introduce three commonly used methods of reading an XML file. They are

   1: Use XmlDocument
   2: Use XmlTextReader
   3: Use Linq to Xml

Here I would like to create an XML file named all methods are based on the XML file Book.xml below, document reads as follows:

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <bookstore>
   3: <-! Record book information ->
   4: <book Type = "compulsory" ISBN = "7-111-19149-2">
   5: <title> Data Structure </ title>
   6: <author> Yan Wei Min </ author>
   7:     <price>30.00</price>
   8:   </book>
   9: <book Type = "compulsory" ISBN = "7-111-19149-3">
  10: <title> type routing and switching type of Internet-based </ title>
  11:     <author>程庆梅</author>
  12:     <price>27.00</price>
  13:   </book>
  14: <book Type = "compulsory" ISBN = "7-111-19149-4">
  15: <title> hardware technology elements </ title>
  16: <author> Li Jican </ author>
  17:     <price>25.00</price>
  18:   </book>
  19: <book Type = "compulsory" ISBN = "7-111-19149-5">
  20: <title> Software Quality Assurance and Management </ title>
  21: <author> Zhushao Min </ author>
  22:     <price>39.00</price>
  23:   </book>
  24: <book Type = "compulsory" ISBN = "7-111-19149-6">
  25: <title> algorithm design and analysis </ title>
  26: <author> Hongmei </ author>
  27:     <price>23.00</price>
  28:   </book>
  29: <book Type = "elective" ISBN = "7-111-19149-1">
  30: <title> computer operating system </ title>
  31:     <author>7-111-19149-1</author>
  32:     <price>28</price>
  33:   </book>
  34: </bookstore>

In order to facilitate reading, I also define an entity class of a book called BookModel, including the following:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5:  
   6: namespace using XmlDocument
   7: {
   8:     public class BookModel
   9:     {
  10:         public BookModel()
  11:         { }
  12:         /// <summary>
  13: Type of course /// corresponding
  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: /// book ISBN number corresponding
  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: /// Title
  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: /// Author
  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: /// price
  58:         /// </summary>
  59:         private double bookPrice;
  60:  
  61:         public double BookPrice
  62:         {
  63:             get { return bookPrice; }
  64:             set { bookPrice = value; }
  65:         }
  66:     }
  67: }

1. Use the XmlDocument.

       Use XmlDocument is a model-based way to read the document structure XML file in an XML file, we can be seen as a XML document declaration (Declare), the element (Element), attributes (Attribute), text (Text) a tree like configuration. a node called root node of the beginning, each node can have its own child nodes. after obtaining a node, the node value may be obtained through a series of property or method ., for example, or some other attributes:

   1: xn represents a node
   2: xn.Name; // this node name
   3: xn.Value; // node value
   4: xn.ChildNodes; // this sub-node to all nodes
   5: xn.ParentNode; // parent node of this node
   6: .......
1.1 to read all the data.
When in use, first declare a XmlDocument object, and then call the Load method to load an XML file from the specified path.
   1: XmlDocument doc = new XmlDocument();
   2: doc.Load(@"..\..\Book.xml");

     You may then be obtained by calling the specified node SelectSingleNode, concrete attribute values ​​obtained by GetAttribute. Referring now code

   1: // root node bookstore
   2: XmlNode xn = xmlDoc.SelectSingleNode("bookstore");
   3:  
   4:  
   5: // Get all the child nodes of the root node
   6: XmlNodeList xnl = xn.ChildNodes;
   7:  
   8: foreach (XmlNode xn1 in xnl)
   9: {
  10:     BookModel bookModel = new BookModel();
  11: // node is an element to convert, to give attribute values ​​of nodes to facilitate
  12:     XmlElement xe = (XmlElement)xn1;
  13: Type // get property values ​​and two properties ISBN
  14:     bookModel.BookISBN = xe.GetAttribute("ISBN").ToString();
  15:     bookModel.BookType = xe.GetAttribute("Type").ToString();
  16: // get all the child nodes of node 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;

       Under normal circumstances, the above code seems to be no problem, but to read the above XML file, an error occurs, the reason is because I'm on top of the XML file there are comments, you can see the third line Book.xml file I just added a comment. comment is also a node type, in the absence of special note, by default it is also a node (node). Therefore, the error will be converted at the junction to the elemental time. " You can not type "System.Xml.XmlComment" cast object to type "System.Xml.XmlElement". "

Snap2_thumb1

Fortunately, it comes with a solution which, when it is read, it tells the compiler to ignore the comment information which amended as follows:

   1: XmlDocument xmlDoc = new XmlDocument();
   2: XmlReaderSettings settings = new XmlReaderSettings();
   3: settings.IgnoreComments = true; // ignore the comments inside the document
   4: XmlReader reader = XmlReader.Create(@"..\..\Book.xml", settings);
   5: xmlDoc.Load(reader);

After the final reading is completed, remember to turn off the reader.

   1: reader.Close();

So that it is error free.

Final results are as follows:

image_thumb8

1.2 adding information of a book.

Add new data to the file, the first thing is to load the entire document by XmlDocument, and then get the root node by calling SelectSingleNode method, created by CreateElement element method, create an attribute with CreateAttribute, with AppendChild the current node in other nodes attached the point on the node with the attribute set SetAttributeNode specific code is as follows:

To load the file and select the node:

   1: XmlDocument doc = new XmlDocument();
   2: doc.Load(@"..\..\Book.xml");
   3: XmlNode root = doc.SelectSingleNode("bookstore");

Create a node, and set properties node:

   1: XmlElement xelKey = doc.CreateElement("book");
   2: XmlAttribute xelType = doc.CreateAttribute("Type");
   3: xelType.InnerText = "adfdsf";
   4: xelKey.SetAttributeNode(xelType);

Create a sub-node:

   1: XmlElement xelAuthor = doc.CreateElement("author");
   2: xelAuthor.InnerText = "dfdsa";
   3: xelKey.AppendChild(xelAuthor);
Finally, the book node to node on the Mount, and save the entire file:
   1: root.AppendChild(xelKey);
   2: doc.Save(@"..\..\Book.xml");

Using the above procedure is appending to an existing file, if you want to cover all the original data, you can change it, use LoadXml method:

   1: XmlDocument doc = new XmlDocument();
   2: doc.LoadXml ( "<bookstore> </ bookstore>"); // use these words, will overwrite all previous data, only increase your data

Directly to the selected root out the back do not select the root SelectSingleNode method, you can directly create nodes, the code above.

1.3 delete certain data

You want to delete a particular node, directly to its parent node, then call RemoveChild method can be, the key question now is how to find this node, the above SelectSingleNode can pass a Xpath table, we come through the ISBN number of the book locate the junction where the book is as follows:

   1: XmlElement xe = xmlDoc.DocumentElement; // DocumentElement Gets the root XmlElement xml document object.
   2: string strPath = string.Format("/bookstore/book[@ISBN=\"{0}\"]", dgvBookInfo.CurrentRow.Cells[1].Value.ToString());
   3: XmlElement selectXe = (XmlElement) xe.SelectSingleNode (strPath); // selectSingleNode The XPath expression to obtain a qualified first node.
   4: selectXe.ParentNode.RemoveChild(selectXe);

"/ bookstore / book [@ISBN = \" {0} \ "]" is a Xpath expression, ISBN number to find the row for that selected ISBN number of the book, knowledge of Xpath, please refer to: XPath syntax

1.4 To amend certain pieces of data

Edit a piece of data, the first is to find a Xpath expression that a node that you want to modify, and then if it is an element, then it directly on this element assignment, if a property, then it is set to use SetAttribute as follows:

   1: XmlElement xe = xmlDoc.DocumentElement; // DocumentElement Gets the root XmlElement xml document object.
   2: string strPath = string.Format("/bookstore/book[@ISBN=\"{0}\"]", dgvBookInfo.CurrentRow.Cells[1].Value.ToString());
   3: XmlElement selectXe = (XmlElement) xe.SelectSingleNode (strPath); // selectSingleNode The XPath expression to obtain a qualified first node.
   4: selectXe.SetAttribute ( "Type", dgvBookInfo.CurrentRow.Cells [0] .Value.ToString ()); // attribute may be increased by a 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. Use XmlTextReader and XmlTextWriter

XmlTextReader form and is XmlTextWriter streams to read and write XML documents.

2.1XmlTextReader

Use XmlTextReader read data when creating a first stream, and then continued down to read a read () method to perform a corresponding operation according to the type of node is read as follows:

   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;

The key attribute is read when you have to know which node has several attributes, and then read by GetAttribute method. Read attribute may also use another method, that is. See the following code by the method 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:     }

Results are as follows:

image_thumb12

2.2XmlTextWriter

XmlTextWriter write the file, the default is overwrite the previous file, if the file name does not exist, it will create this file, first set about, XML file format you want to create,

   1: XmlTextWriter myXmlTextWriter = new XmlTextWriter(@"..\..\Book1.xml", null);
   2: // using the Formatting property to specify what you want to set as XML format. Thus, the sub-elements can be indented by using Indentation and IndentChar property.
   3: myXmlTextWriter.Formatting = Formatting.Indented;

Then can be created by WriteStartElement and WriteElementString element method, this difference between the two is that if there is an element child nodes, so when it was created with WriteStartElement, and then to create sub-elements, created, to be called to tell the corresponding WriteEndElement compiler, is created by WriteElementString to create a single element, with attributes WriteAttributeString created as follows:

   1: XmlTextWriter myXmlTextWriter = new XmlTextWriter(@"..\..\Book1.xml", null);
   2: // using the Formatting property to specify what you want to set as XML format. Thus, the sub-elements can be indented by using Indentation and IndentChar property.
   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#3.0中出现的一个新特性,使用它可以方便的操作许多数据源,也包括XML文件.使用Linq操作XML文件非常的方便,而且也比较简单.下面直接看代码,

先定义 一个方法显示查询出来的数据
   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:        }

3.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:        }

3.2插入一条数据

插入结点和属性都采用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:         }

3.3 删除选中的数据

首先得到选中的那一行,通过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:        }

3.4 删除所有的数据

与上面的类似,选出所有的数据,然后用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:        }

3.5 修改某一记录

首先得到所要修改的某一个结点,然后用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 ( "modified successfully!");
  26:         btnReadAll_Click(sender, e);
  27:     }
  28: }

The final results are as follows:

image_thumb15

Guess you like

Origin www.cnblogs.com/yuer20180726/p/10984234.html