. NET Framework easy XML data processing (5)

Source: Internet
Author: User
Tags xml reader
Design XmlReadWriter class
As mentioned above, XML reader and Writer work independently: reader is read-only and writer only writes data. Assume that your application needs to manage lengthy XML documents with uncertain data. Reader provides a good way to read the content of this document. On the other hand, Writer is a very useful tool for creating XML document snippets. But if you want it to be readable and writable, you need to use XMLDOM. If the actual XML document is very large, another problem occurs. What is the problem? Is it possible to load all the XML documents into the memory and then read and write them? Let's take a look at how to create a Hybrid Flow Analyzer for analyzing large XMLDOM.
Like read-only operations, common XML reader is used to access nodes in sequence. The difference is that you can use XML writer to change the attribute value and node content while reading the data. You use reader to read each node in the source file, and the background writer creates a copy of the node. In this copy, you can add new nodes, ignore or edit other nodes, and edit attribute values. After modification, you can replace the old one with the new one.
A simple and effective method is to copy the Node object from the read-only stream to the write stream. This method can use two methods in the XmlTextWriter class: The WriteAttributes method and the WriteNode method. The WriteAttributes method reads all valid attributes of the node selected in the current reader, and copies the attributes as a separate string to the current output stream. Similarly, the WriteNode method processes other types of nodes except attribute nodes in a similar way. The code snippet shown in Figure 10 demonstrates how to use the two methods above to create a copy of the source XML document, and select to modify some nodes. The XML tree is accessed from the root of the tree, but only nodes of other types except the attribute node type are output. You can integrate Reader and Writer into a new class and design a new interface so that it can read and write streams and access attributes and nodes.
Figure 10 Using the WriteNode Method
XmlTextReader reader = new XmlTextReader (inputFile );
XmlTextWriter writer = new XmlTextWriter (outputFile );

// Configure reader and writer
Writer. Formatting = Formatting. Indented;
Reader. MoveToContent ();

// Write the root node
Writer. WriteStartElement (reader. LocalName );

// Read and output every other node
Int I = 0;
While (reader. Read ())
{
If (I % 2)
Writer. WriteNode (reader, false );
I ++;
}

// Close the root
Writer. WriteEndElement ();

// Close reader and writer
Writer. Close ();
Reader. Close ();
My XmlTextReadWriter class does not inherit from the XmlReader or XmlWriter class. Instead, there are two other classes. One is the operation class based on the read-only stream, and the other is the operation class based on the write-only stream. The XmlTextReadWriter class reads data from the Reader object and writes the data to the Writer object. To meet different requirements, internal Reader and Writer objects are made public through the read-only Reader and Writer attributes. Figure 11 lists some methods for this class:
Figure 11 XmlTextReadWriter Class Methods
Method
Description
AddAttributeChange
Caches all the information needed to perform a change on a node attribute. All the changes cached through this method are processed during a successive call to WriteAttributes.
Read
Simple wrapper around the internal reader's Read method.
WriteAttributes
Specialized version of the writer's WriteAttributes method, writes out all the attributes for the given node, taking into account all the changes cached through the AddAttributeChange method.
WriteEndDocument
Terminates the current document in the writer and closes both the reader and the writer.
WriteStartDocument
Prepares the internal writer to output the document and add a default comment text and the standard XML prolog.

This new class has a Read method, which is a simple encapsulation of the Reader's read method. In addition, it provides the WriterStartDocument and WriteEndDocument methods. They initialize/release (finalize) Internal Reader and writer objects respectively, and process all I/O operations. While reading nodes cyclically, we can directly modify the nodes. For performance reasons, the AddAttributeChange method must be used to modify attributes. All the modifications made to the attributes of a node are stored in a temporary table. Finally, you can call the WriteAttribute method to submit the changes and clear the temporary table.
The code shown in Figure 12 demonstrates the advantage of using the XmlTextReadWriter class to modify attribute values while reading data. In this issue, msdn provides C # and VB source code downloads for the XmlTextReadWriter class (see the link provided at the beginning of this article ).
Figure 12 Changing Attribute Values
Private void ApplyChanges (string nodeName, string attribName,
String oldVal, string newVal)
{
XmlTextReadWriter rw = new XmlTextReadWriter (InputFileName. Text,
OutputFileName. Text );
Rw. WriteStartDocument (true, CommentText. Text );

// Manually modify the root node
Rw. Writer. WriteStartElement (rw. Reader. LocalName );

// Start modifying attributes
// (Attributes of more nodes can be modified)
Rw. AddAttributeChange (nodeName, attribName, oldVal, newVal );

// Circular processing document
While (rw. Read ())
{
Switch (rw. NodeType)
{
Case XmlNodeType. Element:
Rw. Writer. WriteStartElement (rw. Reader. LocalName );
If (nodeName = rw. Reader. LocalName)
// Modify attributes
Rw. WriteAttributes (nodeName );
Else
// Deep copy
Rw. Writer. WriteAttributes (rw. Reader, false );

If (rw. Reader. IsEmptyElement)
Rw. Writer. WriteEndElement ();
Break;
}
}

// Close the root tag
Rw. Writer. WriteEndElement ();

// Close the document and any internal resources
Rw. WriteEndDocument ();
}

The XmlTextReadWriter class can not only read XML documents, but also write XML documents. You can use it to read the content of an XML document. If necessary, you can also use it for some basic update operations. The basic update operation here refers to modifying the value of an existing attribute or the content of a node, or adding a new attribute or node. For more complex operations, it is best to use the XMLDOM analyzer.
Summary
Reader and Writer are the basis for processing XML data in. NET Framework. They provide original APIs for accessing all XML data. Reader is like a new analyzer class, which has the powerful XMLDOM and fast and simple SAX. Writer is designed for simple creation of XML documents. Both Reader and Writer are small parts of the. NET Framework, but they are independent APIs. In this article, we only discuss how to use Reader and Writer to complete some of the main work, introduce the principle mechanism of the verification analyzer, and integrate Reader and writer into a separate class. All of the above classes are lightweight, similar to a cursor-based XMLDOM analyzer.

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.