Detailed C # read the XML instance code _c# tutorial

Source: Internet
Author: User
Tags object model xpath

An XML file is a commonly used file format, such as a WinForm inside a app.config and a Web.config file in a Web application, as well as a number of important sites. XML is a cross-platform, content-dependent technology in an Internet environment and a powerful tool for dealing with structured document information at the moment. XML is a simple data storage language that uses a series of simple tags to describe data that can be built in a convenient way, although XML takes up more space than binary data, but XML is extremely simple and easy to master and use. Microsoft also offers a series of class libraries to help us store XML files in our applications.

"Accessing and then manipulating XML files in a program typically has two models, using the DOM (Document Object model) and the flow model, the advantage of using DOM is that it allows editing and updating of XML documents, random access to data in documents, and XPath queries, but The disadvantage of DOM is that it requires a one-time load of the entire document into memory, which can cause resource problems for large documents. The flow model solves the problem very well, because its access to the XML file is based on the concept of a stream, that is, there is only the current node in memory at any time, but it also has its drawbacks, it is read-only, forward only, and cannot perform backward navigation in the document. ”

I'll explain the three common ways to read XML files. respectively is

1: Use XmlDocument

2: Use XmlTextReader

3: Using LINQ to XML

Here I first create an XML file, named Book.xml, all of the following methods are based on this XML file, the contents of the file are as follows:

 <?xml version= "1.0" encoding= "Utf-8"?> <bookstore> <!--record book information--> <book type= "Compulsory course" isbn= "7-111-19149-2" > <title> data Structure </title> <author> Min </author> <price>30.00<
    /price> </book> <book type= "Compulsory course" isbn= "7-111-19149-3" > <title> Routing and Exchange-type Internet foundation </title> <author> Cheng Qingmei </author> <price>27.00</price> </book> <book type= "Compulsory course" isbn= "7- 111-19149-4 "> <title> computer Hardware technology base </title> <author> Li Jizan </author> <price>25.00</ price> </book> <book type= "Compulsory course" isbn= "7-111-19149-5" > <title> Software Quality assurance and management </title> &L t;author> Zhu Shaomin </author> <price>39.00</price> </book> <book type= "Compulsory course isbn=" 7-111-19 149-6 "> <title> algorithm design and Analysis </title> <author> Wang </author> <price>23.00</price&gt
   ; </book> &LT;book type= "Elective" isbn= "7-111-19149-1" > <title> computer operating system </title> <author>7-111-19149-1</auth or> <price>28</price> </book> </bookstore>

To facilitate reading, I also define the entity class for a book, named Bookmodel, as follows:

 Using System;
   Using System.Collections.Generic;
   Using System.Linq;
   
   Using System.Text; Namespace use XmlDocument {public class Bookmodel {public Bookmodel () {}///&LT;SUMMARY&G
      T
   
      The corresponding course type///</summary> private string BookType;
        public string BookType {get {return booktype;}
      set {BookType = value;}
   
      The ISBN///</summary> private string BOOKISBN corresponding to the///<summary>///book;
        public string Bookisbn {get {return BOOKISBN;}
      set {BOOKISBN = value;}
   
      ///<summary>///title///</summary> private String bookname;
        public string BookName {get {return bookname;}
      set {bookname = value;}
   
      }///<summary>///author///</summary> private string Bookauthor; public string BookauthoR {get {Bookauthor;}
      set {Bookauthor = value;}
   
      ///<summary>///Price///</summary> private double bookprice;
        Public double Bookprice {get {return bookprice;}
      set {Bookprice = value;}

 }
    }
  }

1. Use XmlDocument.

Using XmlDocument is a way to read XML files based on the document structure model. In an XML file, we can think of XML as a document declaration (Declare), an element, an attribute, a literal (text) such as a tree. The beginning of a node is called the root node, each node can have its own child nodes. After a node is obtained, the value of the node or some other properties can be obtained by a series of properties or methods. For example:

  Xn represents a node
   xn. name;//the name of this node
   xn. value;//the value of this node
   xn. childnodes;//all the sub nodes of this node
   xn. parentnode;//The parent node of this node ....
   

1.1 Read all the data.

When used, first declare a XmlDocument object, and then call the Load method to load the XML file from the specified path.

XmlDocument doc = new XmlDocument ();
Doc. Load (@). \.. \book.xml ");

The specified node can then be obtained by calling selectSingleNode, and the specific property value is obtained by getattribute. See the code below

/Get root node bookstore XmlNode xn = xmldoc.selectsinglenode ("bookstore"); Gets all the child nodes of the root node xmlnodelist xnl = xn.
   
   ChildNodes;
    foreach (XmlNode xn1 in xnl) {Bookmodel Bookmodel = new Bookmodel ();
    The node is converted to an element to make it easy to get the attribute value of the node XmlElement XE = (XmlElement) xn1; Gets the property value of type and ISBN two properties bookmodel.bookisbn = Xe. GetAttribute ("ISBN").
    ToString (); Bookmodel.booktype = Xe. GetAttribute ("Type").
    ToString (); Gets all the child nodes of the book node XmlNodeList xnl0 = Xe.
    ChildNodes; Bookmodel.bookname=xnl0. Item (0).
    InnerText; Bookmodel.bookauthor=xnl0. Item (1).
    InnerText; Bookmodel.bookprice=convert.todouble (xnl0. Item (2).
    InnerText);
  Bookmodelist.add (Bookmodel);

} Dgvbookinfo.datasource = Bookmodelist; 

Under normal circumstances, the above code seems to have no problem, but for reading the above XML file, it will be wrong, because I have a comment in the above XML file, you can refer to the third line in the Book.xml file, I casually add a comment. Annotation is also a type of node, In the absence of a special description, it is also a node (node) by default. So when you convert a node to an element, you get an error. An object of type ' System.Xml.XmlComment cannot be cast to type ' System.Xml.XmlElement '. "

Fortunately, it comes with a solution, that is, when reading, tell the compiler to let it ignore the inside of the annotation information. Modify the following:

XmlDocument xmldoc = new XmlDocument ();
XmlReaderSettings settings = new XmlReaderSettings ();
Settings. Ignorecomments = true;//ignores comments in the document
XmlReader reader = xmlreader.create (@). \.. \book.xml ", settings);
Xmldoc.load (reader);

After the last read, remember to turn off reader.

 Reader. Close ();

So that it doesn't have an error.

The results of the final run are as follows:

1.2 Add a book to the information.

When you add new data to a file, you first load the entire document through XmlDocument, then get the root node by calling the selectSingleNode method, create the element by the CreateElement method, and create the attribute with CreateAttribute. , the current node is hooked up with appendchild to other nodes, and the properties of the nodes are set with Setattributenode. The specific code is as follows:

Load the file and select the node:

XmlDocument doc = new XmlDocument ();
Doc. Load (@). \.. \book.xml ");
XmlNode root = Doc. selectSingleNode ("bookstore");

Create a node and set the properties of the node:

  XmlElement xelkey = doc. CreateElement ("book");
   XmlAttribute Xeltype = doc. CreateAttribute ("Type");
   Xeltype.innertext = "ADFDSF";
   Xelkey.setattributenode (Xeltype);

To create a child node:

  XmlElement xelauthor = doc. CreateElement ("author");
   Xelauthor.innertext = "DFDSA";
   Xelkey.appendchild (Xelauthor);

Finally, the book node is hooked up to the node, and the entire file is saved:

Root. AppendChild (Xelkey);
Doc. Save (@). \.. \book.xml ");

Using the above method, is to append the data to the existing file, if you want to overwrite all the original data, you can change, using the Loadxml method:

  XmlDocument doc = new XmlDocument ();
   Doc.

Select the root node directly, the following do not use the selectSingleNode method to select the root node, directly create the node, the code ditto.

1.3 Delete a certain data

To delete a node, locate its parent node directly, and then call the RemoveChild method, the key question now is how to find the node, where the selectSingleNode can pass in an XPath table, We found the book's node by the book's ISBN. as follows:

 XmlElement XE = xmldoc.documentelement; DocumentElement gets the root xmlelement of the XML Document object.
   String strpath = String. Format ("/bookstore/book[@ISBN =\" {0}\ "]", dgvbookinfo.currentrow.cells[1]. Value.tostring ());
   XmlElement selectxe = (XmlElement) Xe. selectSingleNode (strpath); selectSingleNode The first node that meets the criteria according to an XPath expression.
   SelectXe.ParentNode.RemoveChild (SELECTXE);

"/bookstore/book[@ISBN =\" {0}\ "]" is an XPath expression that finds the book with an ISBN number for the selected line of an ISBN, for the knowledge of XPath, refer to: XPath syntax

1.4 Modify a certain piece of data

To modify a piece of data, the first is to use an XPath expression to find the desired change of the node, and then, if the element, directly to the element assignment, if it is the attribute, the SetAttribute method set.

  XmlElement XE = xmldoc.documentelement; DocumentElement gets the root xmlelement of the XML Document object.
   String strpath = String. Format ("/bookstore/book[@ISBN =\" {0}\ "]", dgvbookinfo.currentrow.cells[1]. Value.tostring ());
   XmlElement selectxe = (XmlElement) Xe. selectSingleNode (strpath); selectSingleNode The first node that meets the criteria according to an XPath expression.
   Selectxe.setattribute ("Type", Dgvbookinfo.currentrow.cells[0]. Value.tostring ());//You can also add a property
   selectxe.getelementsbytagname ("title") by SetAttribute. Item (0). innertext = dgvbookinfo.currentrow.cells[2]. Value.tostring ();
   Selectxe.getelementsbytagname ("Author"). Item (0). innertext = dgvbookinfo.currentrow.cells[3]. Value.tostring ();
   Selectxe.getelementsbytagname ("Price"). Item (0). innertext = Dgvbookinfo.currentrow.cells[4]. Value.tostring ();
   Xmldoc.save (@ "...) \.. \book.xml ");

2. Use of XmlTextReader and XmlTextWriter

XmlTextReader and XmlTextWriter read and write XML files in a streaming form.

2.1XmlTextReader

When you use XmlTextReader to read data, you first create a stream, and then use the Read () method to continuously read down, according to the type of node to read the corresponding operation. as follows:

 XmlTextReader reader = new XmlTextReader (@). \..
        \book.xml ");
        list<bookmodel> modellist = new list<bookmodel> ();
        Bookmodel model = new Bookmodel (); while (reader. Read ()) {if (reader). NodeType = = xmlnodetype.element) {if reader. Name = = "book") {model. BookType = reader.
              GetAttribute (0); Model. BOOKISBN = reader.
            GetAttribute (1); } if (reader. Name = = "title") {model. Bookname=reader. Readelementstring ().
            Trim (); } if (reader. Name = = "Author") {model. Bookauthor = reader. Readelementstring ().
            Trim (); } if (reader. Name = = "Price") {model. Bookprice = convert.todouble (reader. Readelementstring ().
            Trim ()); } if (reader. NodeType = = xmlnodetype.endelement) {modellist.ADD (model);
          Model = new Bookmodel ();
        } modellist.removeat (modellist.count-1);
 This.dgvBookInfo.DataSource = modellist;

The key is that when you read the attribute, you first know which node has several properties and then read the GetAttribute method. Read properties can also be used in another way, which is to use the MoveToAttribute method. See the following code:

  if (reader. Name = = "book"
     } {for
       (int i = 0; i < reader.) Attributecount; i++)
       {
         reader. MoveToAttribute (i);
         String str = "attribute:" + reader. Name + "=" + Reader. Value;
       }
       Model. BookType = reader. GetAttribute (0);
       Model. BOOKISBN = reader. GetAttribute (1);
    }

The effect is as follows:

2.2XmlTextWriter

When XmlTextWriter writes a file, the default is to overwrite the previous file, and if the filename does not exist, it will create the file. First set up the XML file format that you want to create,

 XmlTextWriter myXmlTextWriter = new XmlTextWriter (@). \.. \book1.xml ", null);
   Use the Formatting property to specify what format you want the XML to be formatted. This allows the child elements to be indented by using the indentation and IndentChar properties.
   myxmltextwriter.formatting = formatting.indented;

The

can then create elements through the WriteStartElement and WriteElementString methods, the difference being that if there are elements of a child node, then the creation is done with WriteStartElement, and then the child element is created. Once created, you call the corresponding writeendelement to tell the compiler, create it, use writeelementstring to create a single element, and use WriteAttributeString to create the attribute. As follows:

 XmlTextWriter myXmlTextWriter = new XmlTextWriter (@). \..
        \book1.xml ", NULL); Use the Formatting property to specify what format you want the XML to be formatted.
        This allows the child elements to be indented by using the indentation and IndentChar properties.
   
        myXmlTextWriter.Formatting = formatting.indented;
        Myxmltextwriter.writestartdocument (FALSE);
   
        Myxmltextwriter.writestartelement ("bookstore");
        myXmlTextWriter.WriteComment ("Record the information of the book");
   
        Myxmltextwriter.writestartelement ("book");
        myXmlTextWriter.WriteAttributeString ("Type", "optional");
   
        myXmlTextWriter.WriteAttributeString ("ISBN", "111111111");
        Myxmltextwriter.writeelementstring ("Author", "John");
        Myxmltextwriter.writeelementstring ("title", "Career planning");
   
        Myxmltextwriter.writeelementstring ("Price", "16.00");
        Myxmltextwriter.writeendelement ();
   
        Myxmltextwriter.writeendelement ();
        Myxmltextwriter.flush ();

Myxmltextwriter.close (); 

3. Use LINQ to XML.

LINQ is a new feature that appears in c#3.0, and it makes it easy to manipulate many data sources, including XML files. Using LINQ to manipulate XML files is convenient and simple. See the code directly below,

First, define a method to display the queried data.

  private void Showinfobyelements (ienumerable<xelement> elements)
      {
        list<bookmodel> modellist = New List<bookmodel> ();
        foreach (var ele in elements)
        {
          Bookmodel model = new Bookmodel ();
          Model. Bookauthor = Ele. Element ("Author"). Value;
          Model. BookName = Ele. Element ("title"). Value;
          Model. Bookprice = Convert.todouble (ele. Element ("Price"). Value);
          Model. Bookisbn=ele. Attribute ("ISBN"). Value;
          Model. Booktype=ele. Attribute ("Type"). Value;
          
          Modellist.add (model);
        }
        Dgvbookinfo.datasource = modellist;
      }

3.1 Read all the data

Directly find the node with the element book, and then iterate through all the results.

  private void Btnreadall_click (object sender, EventArgs e)
      {
        XElement xe = Xelement.load (@). \.. \book.xml ");
        ienumerable<xelement> elements = from ele in XE. Elements ("book")
                         select Ele;
        Showinfobyelements (elements);
      }

3.2 Inserting a piece of data

Inserting nodes and attributes takes the new method, as follows:

  private void Btninsert_click (object sender, EventArgs e)
       {
         XElement xe = Xelement.load (@). \.. \book.xml ");
         XElement record = new XElement (The New XElement ("Book
         ",
         new XAttribute ("Type", "elective"),
         new XAttribute ("ISBN"), "7-111-19149-1"),
         New XElement ("title", "Computer operating System"),
         New XElement ("Author", "7-111-19149-1"),
        New XElement ("Price", 28.00));
        Xe. ADD (record);
        Xe. Save (@). \.. \book.xml ");
        MessageBox.Show ("Insert succeeded!") ");
        Btnreadall_click (sender, E);
      }

3.3 Delete the selected data

First get the selected line, find this element by the ISBN, and delete it directly with the Remove method, as follows:

  private void Btndelete_click (object sender, EventArgs e)
      {
        if (dgvbookinfo.currentrow!= null)
        {
          // DGVBOOKINFO.CURRENTROW.CELLS[1] corresponds to the ISBN number
          string id = dgvbookinfo.currentrow.cells[1]. Value.tostring ();
          XElement XE = Xelement.load (@). \.. \book.xml ");
          ienumerable<xelement> elements = from ele in XE. Elements ("book")
                           where (string) ele. Attribute ("ISBN") = = ID
                          select ele;
         {
          if (elements). Count () > 0)
            elements. A (). Remove ();
          }
          Xe. Save (@). \.. \book.xml ");
          MessageBox.Show ("Delete succeeded!") ");
          Btnreadall_click (sender, E);
   
        }
      }

3.4 Delete all the data

Similar to the above, select all the data and then use the Remove method, as follows:

  private void Btndeleteall_click (object sender, EventArgs e)
      {
        XElement xe = Xelement.load (@). \.. \book.xml ");
        ienumerable<xelement> elements = from ele in XE. Elements ("book")
                         select Ele;
        if (elements. Count () > 0)
        {
          elements. Remove ();
        }
        Xe. Save (@). \.. \book.xml ");
        MessageBox.Show ("Delete succeeded!") ");
        Btnreadall_click (sender, E);
      }

3.5 Modify a record

First get the node to be modified, and then use Setattributevalue to modify the attributes, using Replacenodes to modify the node elements. As follows:

  private void Btnsave_click (object sender, EventArgs e) {XElement XE = Xelement.load (@). \..
     \book.xml "); if (Dgvbookinfo.currentrow!= null) {//dgvbookinfo.currentrow.cells[1] corresponds to an ISBN string id = dgvbookinfo . CURRENTROW.CELLS[1].
       Value.tostring (); ienumerable<xelement> element = from ele in XE. Elements ("book") where Ele. Attribute ("ISBN").
      Value = = ID Select ele; if (element. Count () > 0) {XElement a = element.
        A (); Sets the new property A. Setattributevalue ("Type", Dgvbookinfo.currentrow.cells[0].
        Value.tostring ()); Replaces the new node in a. Replacenodes (New XElement ("title", Dgvbookinfo.currentrow.cells[2). Value.tostring ()), New XElement ("Author", dgvbookinfo.currentrow.cells[3). Value.tostring ()), New XElement ("Price", (double) dgvbookinfo.currentrow.cells[4].
      Value)); Xe. Save (@). \.. \boOk.xml "); MessageBox.Show ("Modify success!")
      ");
    Btnreadall_click (sender, E); }
  }

The final effect is as follows:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.