Easy XML data processing in. NET Framework (1)

Source: Internet
Author: User
Tags object serialization xml reader

Easy XML data processing in. NET Framework (1)
This document assumes that you are familiar with XML and. NET Framework.

In. NET Framework, the xmltextreader and xmltextwriter classes provide read and write operations on XML data. In this article, the author describes the architecture of the XML reader and how they are combined with the xmldom and the sax interpreter. The author also demonstrated how to use a reader to analyze and verify XML documents, how to create well-formed XML documents, and how to use functions to read/write large XML documents encoded Based on base64 and binhex. Finally, the author explains how to implement a stream-based read/write analyzer, which encapsulates all the readers in a separate class.

About three years ago, I attended a software seminar on "No XML, no programming future ". XML is indeed developing step by step. It has been embedded in. NET Framework. In this article, I will explain the roles and internal features of the APIs used to process XML documents in. NET Framework. Then I will demonstrate some common functions.

XML from MSXML to. net

Before. NET Framework appeared, you used to use the MSXML service-a com-based class library-to write windows XML drivers. Unlike classes in the. NET Framework, some code in the MSXML class library is deeper than the API, and it is completely embedded at the underlying layer of the operating system. MSXML can indeed communicate with your application, but it cannot really be combined with the external environment.

The MSXML class library can be imported in Win32 and used in CLR, but it can only be used as an external server component. However, Applications Based on. NET Framework can directly use XML classes and Other Namespaces of. NET Framework, and the written code is easy to read.

As an independent component, MSXML analyzer provides some advanced features such as Asynchronous analysis. This feature is available in.. NET Framework and. other classes in the net framework are not provided. However, the integration of XML classes in the net framework with other classes can easily obtain the same functions, on this basis, you can add more features.

The XML class in. NET Framework provides basic functions for analyzing, querying, and transforming XML data. In. NET Framework, you can find classes that support XPath query and XSLT conversion, and read/write XML documents. In addition ,. NET framework also contains other XML processing classes, such as object serialization (xmlserializer and the soapformatter class), application configuration (appsettingsreader class), and data storage (Dataset class ). In this article, I will only discuss classes that implement basic xml I/O operations.

XML Analysis Mode

Since XML is a markup language, there should be a tool to analyze and understand the information stored in the document according to certain syntaxes. This tool is an XML analyzer-a component used to read markup text and return objects of the specified platform.

All XML analyzers, no matter which operating platform they belong to, are classified into two types: tree-based or event-based processors. These two types are usually implemented using xmldom (the Microsoft XML Document Object Model) and SAX (Simple API for XML. Xmldom analyzer is a common tree-based API that treats XML documents as a memory structure tree. The sax analyzer is an event-based API that processes every element in the XML data stream (it puts XML data into the stream for processing ). Generally, Dom can be loaded and executed by a sax stream. Therefore, these two types of processing are not mutually exclusive.

In general, the comparison between the sax analyzer and the xmldom analyzer is quite different in their analysis modes. Xmldom is well defined in its functionalition set. You cannot extend it. When processing a large file, it takes a lot of memory space to process the huge set of functionalition.

The sax analyzer uses client applications to Process Analysis events through instances of objects on the existing specified platform. The sax analyzer controls the entire processing process and "releases" the data to the processing program, which accepts or rejects the data in turn. This mode requires only a small amount of memory space.

. NET Framework fully supports the xmldom mode, but it does not support the sax mode. Why? Because. NET Framework supports two different analysis modes: xmldom analyzer and XML reader. It obviously does not support the sax analyzer, but it does not mean it does not provide functions similar to the sax analyzer. All the functions of the XML reader sax can be easily implemented and used more effectively. Unlike the sax analyzer, the. NET Framework reader operates under the client application. In this way, the application itself can only "launch" The actually needed data and then jump out of the XML data stream. The sax analysis mode must process all useful and useless information for applications.

A reader works based on the. NET Framework stream mode, which is similar to a database cursor. Interestingly, classes similar to the cursor Analysis Mode provide underlying support for xmldom analyzer in. NET Framework. The xmlreader and xmlwriter abstract classes are the basic classes of XML classes in all. Net frameworks, including the xmldom class, ADO. Net Driver Class, and configuration class. Therefore, in. NET Framework, you have two optional methods to process XML data. Use the xmlreader and xmlwriter classes to directly process XML data, or use the xmldom mode for processing. For more information about reading documents in. NET Framework, see the cutting edge topic article published in The August 2002 issue of msdn.

Xmlreader class

XML Reader supports a programming interface used to connect XML documents and "launch" the data you want. If you have a deeper understanding of the reader, you will find that the reader works in a way similar to how our desktop applications extract data from the database. Database Service returns a cursor object that contains all query result sets and returns a reference to the start address of the target dataset. The XML reader client receives a reference pointing to the reader instance. This instance extracts the underlying data streams and presents the retrieved data as an XML tree. The reader class provides read-only and forward cursors. You can use the method provided by the reader class to scroll the cursor to traverse each piece of data in the result set.

From the reader, the XML document is not a label text file, but a serialized node set. It is a special cursor mode in. NET Framework. In. NET Framework, you cannot find any other similar API function.

The reader and xmldom analyzer are different. An XML reader is read-only and has no concept of parent, child, ancestor, or sibling node. In. NET Framework, reading and writing XML documents is divided into two completely different functions, which are completed by the xmlreader and xmlwriter classes respectively. To edit an XML document, you can use the xmldom analyzer or design a class to implement these two functions. Let's start to analyze the reader's program functions.

Xmlreader is an abstract class. You can inherit and extend its functions. User Programs are generally based on the following three types: xmltextreader, xmlvalidatingreader, or xmlnodereader class. All these classes have attributes and the fig method. It should be noted that the values of some attributes depend on an actual reader class. Different classes may be different from the base class. Therefore, the description of each attribute in Figure 1 is based on the base class. For example, the canresolveentity attribute returns only true in the xmlvalidatingreader class, but can be set to false in other reader classes. Similarly, the actual return values of some methods in Figure 2 may be different for different classes. For example, if the node type is not an element node, the return value type of all methods containing atrributes is void.

The xmltextreader class uses a read-only method to quickly access the XML data stream. The reader first verifies whether the XML document is in good format. If not, an exception is thrown. Xmltextreader checks whether the DTD format is good, but does not use the DTD to verify the document. Xmltextreader uses the XML document file name, or its url, or loads an XML document from the file stream, and then quickly processes XML document data. If you need to verify the document data, you can use the xmlvalidatingreader class.

You can use multiple methods to create an xmltextreader class instance, load files from the hard disk, or load files from the URL address, stream (streams), and read XML document data from the text:

Xmltextreader reader = new xmltextreader (File );

Note that all public constructors of the xmltextreader class require you to specify a data source, which can be stream, file, or other data sources. Xmltextreader's default constructor is protected, so it cannot be used directly. Like all reader classes in the. NET Framework (such as the sqldatareader class), once the reader object is connected and opened, you can use the read method to access data. At the beginning, only the read method can be used to move the pointer to the first element. Then, we can use the read method or other methods (such as Skip, movetocontent, and readinnerxml) to move the pointer to the next node element. To process the content of the entire XML document, use a loop to traverse the document content based on the return value of the read method, because the read method returns a Boolean value. When reading the End Node of the document, the read method returns false; otherwise, it returns true.

 

Figure 3 outputting an XML document node Layout

String getxmlfilenodelayout (string file)
{
// Create an xmltextreader class to point it to the target XML document
Xmltextreader reader = new xmltextreader (File );
 
// Cyclically retrieve the node text and put it into the stringwriter object instance
Stringwriter writer = new stringwriter ();
String tabprefix = "";
 
While (reader. Read ())
{
// Write Start flag. If the node type is element
If (reader. nodetype = xmlnodetype. element)
{
// Add the reader. Depth tab Based on the depth of the node where the element is located, and then write the element name to <>.
Tabprefix = new string ('/t', reader. Depth );
Writer. writeline ("{0 }<{ 1}>", tabprefix, reader. Name );
}
Else
{
// Write end flag. If the node type is element
If (reader. nodetype = xmlnodetype. endelement)
{
Tabprefix = new string ('/t', reader. Depth );
Writer. writeline ("{0} </{1}>", tabprefix, reader. Name );
}
}
}
 
// Output to the screen
String Buf = writer. tostring ();
Writer. Close ();
 
// Close the stream
Reader. Close ();
 
Return Buf;
}
 

Figure 3 demonstrates a simple function for outputting node elements of a given XML document. This function first opens an XML document and then processes all the content in the XML document cyclically. Each time you call the read method, the reader pointer moves down a node. In most cases, the read method can be used to process element nodes, but sometimes, when you move from a node to the next node, it may be moving between two different types of nodes. However, the read method cannot move between attribute nodes. The movetocontent method of the Reader allows the pointer to jump from the header node to the first content node. You can also use the Skip method to move pointers in processinginstruction, documenttype, comment, whitespace, and significantwhitespace nodes.
Each node type is one of the xmlnodetype enumeration values. In the code shown in 3, we only use the two types: element and endelement. The output source code re-customizes the original document structure. It discards or ignores the attributes and node content of the XML element, and only outputs the element node name. Suppose we use the following XML snippet:

<Mags>
<Mag name = "msdn Magazine">
Msdn magazine
</MAG>
<Mag name = "msdn Voices">
Msdn voices
</MAG>
</Mags>
The output result of the above program is as follows:

<Mags>
<Mag>
</MAG>
<Mag>
</MAG>
</Mags>
The subnode indentation is set based on the reader's depth attribute (depth attribute). The depth attribute returns an integer representing the nested hierarchy of the current node. All text is placed in the stringwriter object (a stream-based class that encapsulates the strigbuilder class is very convenient ).
As mentioned above, the reader does not automatically access attribute nodes through the read method. To access the attribute node set of the current element, you must use a simple loop controlled by the return value of the movetonextattribute method to traverse the set. The following code accesses all the attributes of the current node and combines the attribute name and its value with a comma to form a string:
If (reader. hasattributes)
While (reader. movetonextattribute ())
BUF + = reader. Name + "=/" "+ reader. Value + "/",";
Reader. movetoelement ();
When you complete attribute set processing, call the movetoelement method to return the pointer to the element node to which the attribute belongs. To be accurate, the movetoelement method is not a real moving pointer, because the pointer has never been removed from the element node when processing the attribute set. The movetoelement method only points to an internal Member and obtains the value of the Member in sequence. For example, you can use the name attribute to obtain the attribute name of an attribute, and then call the movetoelement method to move the pointer to the element node to which it belongs. However, when you do not need to process other nodes, you do not have to call the movetoelement method.

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.