Code explanation of three implementations of C # read XML

Source: Internet
Author: User
XML file is a commonly used file format, this article mainly describes the C # read XML three ways to implement, mainly XmlDocument, XmlTextReader, Linq to XML, interested can understand.

Objective

The XML file is a common file format, such as the app. config in WinForm and the Web. config file in the website, as well as a number of important venues. (similar to JSON) Microsoft also offers a range of class libraries to help us store XML files in our applications

There are two general models for accessing and manipulating XML files in a program:

Dom (Document Object Model): The advantage of using the DOM is that it allows editing and updating of XML documents, random access to the data in the document, and the use of XPath queries, but the disadvantage of DOM is that it requires a one-time loading of the entire document into memory, for large documents, This can cause resource problems.

Flow model: The flow model solves this problem very well because its access to the XML file is based on the concept of flow, that is, at any time in memory only the current node, but it also has its shortcomings, it is read-only, forward-only, not in the document to perform a backward navigation operation.

The three ways to read XML files in C # are as follows:

1. Using XmlDocument (DOM mode)

2. Using XmlTextReader (Stream mode)

3. Using LINQ to XML (LINQ mode)

Read using the XmlDocument method

Using XmlDocument is a way to read an XML file based on a document-structured model. In an XML file, we can think of XML as being declared by a document (Declare), element, attribute (Attribute), literal (text) And so on. The first node is called the root node, and each node can have its own sub-node. After a node is obtained, the value of the node or some other properties can be obtained through 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 is xn. childnodes;//all the sub-nodes of this node xn. parentnode;//The parent node of this node.

Read all data

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

Bookmodel is a book model

#region XmlDocument read public static void Xmldocumentreaddemo () {//list list<bookmodel> bookmodelist = new List<b  Ookmodel> ();  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 ();  XmlReaderSettings settings = new XmlReaderSettings (); Settings. Ignorecomments = true;//ignores the annotation using in the document (XmlReader reader = xmlreader.create (@ "D:/demo.xml", Settings)) {Doc.    Load (reader); Doc.    Load (@ "D:/demo.xml"); You can then get the specified node by calling selectSingleNode and get the specific property value by GetAttribute. See the code below//Get root node bookstore XmlNode xn = doc.    selectSingleNode ("bookstore"); Get 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, which makes it easy to get the attribute value of the node XmlElement XE = (XmlElement) xn1; Get the property value of type and ISBN two properties bookmodel.bookisbn = Xe. GetAttribute ("ISBN").      ToString (); Bookmodel.booktype = Xe. GetAttribute ("Type").      ToString (); Get 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); }} bookmodelist.add (new Bookmodel ());} #endregion XmlDocument Read

The results of the operation are as follows:

Read using the XmlTextReader method

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

#region xmltextreaderdemopublic static void Xmltextreaderdemo () {XmlTextReader reader = new XmlTextReader (@ "D:/demo.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 ("Type"); Model. BOOKISBN = reader.      GetAttribute ("ISBN"); } if (reader. Name = = "title") {model. BookName = reader.      Readelementcontentasstring (); } if (reader. Name = = "Author") {model. Bookauthor = reader. Readelementstring ().      Trim (); } if (reader. Name = = "Price") {model. Bookprice = convert.todouble (reader. Readelementstring ().      Trim ()); }//for (int i=0;i<reader. attributecount;i++)//{//reader.      MoveToAttribute (i); }} if (reader.      NodeType = = xmlnodetype.endelement) {modellist.add (model); Model = New Bookmodel (); }} reader.  Close (); Modellist.add (New Bookmodel ());} #endregion Xmltextreaderdemo

Reading using LINQ to XML

LINQ is a new feature in c#3.0 that makes it easy to manipulate many data sources, including XML files. Using LINQ to manipulate XML files is very convenient and simple.

The using system.linq;using System.Xml.Linq must be referenced;

#region Read all data XElement XE = Xelement.load (@ "D:/demolinq.xml");//xe. Descendantsvar elements = from ele in XE. Elements ()        select Ele; list<bookmodel> modellist = new list<bookmodel> (); foreach (var ele in elements) {  Bookmodel model = new Boo Kmodel ();  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);} Modellist.add (New Bookmodel ()); #endregion Read all the data

Summarize

The advantages of the 1.XmlDocument method are easy to find

2.XmlTextReader method is the stream read memory take up less

The newest method of 3.Linq to XML is also the recommended method, the code is less easy to understand

The above is the C # read XML three ways to implement the content of the code, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.