Use the XML guide in C # To Read XML

Source: Internet
Author: User

For XML, I think everyone knows it well. I don't need to bother to describe what it is. I think XML will surely shine in the future of Web development, XML is a scalable markup language, which allows enterprises to develop their own data formats, data is transmitted over the network according to this format and then converted into the desired format through XSLT, which easily solves the problem of incompatible data formats. For Internet data transmission, I think this is the most attractive place for our programmers!

Our topic today is not about the advantages of XML, but about how to use XML in C. Next, let's take a look at some basic theoretical knowledge about accessing XML using a program.

Two access models:

There are two models for accessing and then operating XML files in a program: DOM (Document Object Model) and stream model. The advantage of DOM is that it allows editing and updating XML documents, you can randomly access the data in the document and use XPath for query. However, the disadvantage of DOM is that it needs to load the entire document to the memory at a time. For large documents, this may cause resource problems. The stream model solves this problem well because it uses the stream concept to access XML files, that is, it only has the current node in the memory at any time, but it also has its shortcomings. It is read-only and only forward, and cannot perform backward navigation in the document. Although each has its own merits, we can also use the two in the program to complement each other! Today, we will mainly discuss XML reading. Let's discuss the stream model in detail!

Variations in the stream model:

The stream model iterates one node in the XML document each time. It is suitable for processing large documents and consumes less memory. The stream model has two variants: the "push" model and the "pull" model.

The push model is also commonly referred to as SAX. SAX is an event-driven model. That is to say, every time it discovers a node, it uses the PUSH model to trigger an event, however, we must write the processing programs for these events, which is very inflexible and troublesome.

. NET uses the implementation scheme based on the "pull" model. When traversing a document, the "pull" model will pull the part of the document that is interested from the reader without triggering events, allow us to access documents in a programmatic manner, which greatly improves flexibility. In terms of performance, the "pull" model can be used to process nodes selectively. Every time a node is found in SAX, it notifies the client, the "pull" model can improve the overall efficiency of the Application. In. NET, the "pull" model is implemented as an XmlReader class. Let's take a look at the inheritance structure of this class:


Let's talk about the XmlTextReader class in this architecture. This class provides the ability to read Xml files. It can verify whether the documents are in good format. If not, this class will throw an XmlException exception during reading. You can use some methods provided by this class to read, filter, and obtain the node name and value. Please remember: xmlTextReader is based on the implementation of the stream model. In an inappropriate analogy, the XML file is like a water source. When the gate is opened, the water flow will flow, and it will not flow back. The memory only contains the current node at any time. You can use the Read () method of the XmlTextReader class to Read the next node. Now, let's look at an example. You should pay attention to the actual programming, right. Let's take a look at the running effect before reading the code!


Example1 traverses the document to read data, Example2 and Example3 obtain the node type, Example4 filters the document to get only the data content, Example5 gets the attribute node, Example6 gets the namespace, and Example7 shows the entire XML document, to this end, I specifically write a class to encapsulate the above functions. The code for this class is as follows:


// Configure //---------------------------------------------------------------------------------------------------
// The XmlReader class is used for reading Xml files. The following describes the class:
//
// Attributes (attribute ):
// ListBox: set this attribute to obtain the client control to display the content of the file read. (The ListBox control is used here)
// XmlPath: set this attribute to obtain the absolute path of a specified Xml file.
//
// Basilic Using (important reference ):
// System. Xml: This namespace encapsulates common classes for Xml operations. The XmlTextReader class is used in this class.
// XmlTextReader: This class provides the ability to read Xml files. It can verify whether the file format is good. If it is not a formatted Xml file, this class will throw an XmlException exception during reading. You can use
// Some methods are used to read, filter, and obtain the node name and value.
//
// Bool XmlTextReader. Read (): reads the next node in the stream. After reading the last node, call this method again. This method returns false.
// XmlNodeType XmlTextReader. NodeType: Type of the current node returned by this attribute
// XmlNodeType. Element Node
// XmlNodeType. EndElement End Element Node
// The first node of the XmlNodeType. XmlDeclaration document
// XmlNodeType. Text node
// Bool XmlTextReader. HasAttributes: whether the current node has any attribute. true or false is returned.
// String XmlTextReader. Name: returns the Name of the current node.
// String XmlTextReader. Value: returns the Value of the current node.
// String XmlTextReader. LocalName: returns the local name of the current node.
// String XmlTextReader. NamespaceURI: returns the namespace URI of the current node.
// String XmlTextReader. Prefix: returns the Prefix of the current node.
// Bool XmlTextReader. MoveToNextAttribute (): Move to the next attribute of the current node
// Configure //---------------------------------------------------------------------------------------------------

Namespace XMLReading
{
Using System;
Using System. Xml;
Using System. Windows. Forms;
Using System. ComponentModel;

/// <Summary>
/// Xml file Reader
/// </Summary>

Public class XmlReader: IDisposable
{
Private string _ xmlPath;
Private const string _ errMsg = "Error Occurred While Reading ";
Private ListBox _ listBox;
Private XmlTextReader xmlTxtRd;

# Region XmlReader Constructor

Public XmlReader ()
{
This. _ xmlPath = string. Empty;
This. _ listBox = null;
This. xmlTxtRd = null;
}

/// <Summary>
/// Constructor
/// </Summary>
/// <Param name = "_ xmlPath"> absolute path of the xml file </param>
/// <Param name = "_ listBox"> The listBox is used to display xml. </param>

Public XmlReader (string _ xmlPath, ListBox _ listBox)
{
This. _ xmlPath = _ xmlPath;
This. _ listBox = _ listBox;
This. xmlTxtRd = null;
}

# Endregion
# Region XmlReader resource Release Method

/// <Summary>
/// Clear all resources in use for this object

/// </Summary>

Public void Dispose ()
{
This. Dispose (true );
GC. SuppressFinalize (this );
}

/// <Summary>
/// Release the instance variable of this object
/// </Summary>
/// <Param name = "disposing"> </param>

Protected virtual void Dispose (bool disposing)
{
If (! Disposing)
Return;
If (this. xmlTxtRd! = Null)
{
This. xmlTxtRd. Close ();
This. xmlTxtRd = null;
}

If (this. _ xmlPath! = Null)
{
This. _ xmlPath = null;
}
}

# Endregion
# Region XmlReader attributes

There are 3 pages in this news. Currently, there are 3 pages in 1st.


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.