Easily process XML data in the. NET Framework (v)

Source: Internet
Author: User
Tags access properties add object copy net string xml reader access
xml| Data  Design Xmlreadwriter class

As mentioned earlier, XML reader and writer are working independently: reader-only, writer write only. Suppose your application manages a lengthy XML document, and the document has indeterminate data. Reader provides a good way to read the contents of the document. Writer, on the other hand, is a very useful tool for creating snippets of XML documents, but if you want it to be readable and writable, then you need to use XMLDOM. If the actual XML document is very large, then a problem arises, what is the problem? Is this XML document loaded into memory and then read and written? Let's take a look at how to build a mixed flow analyzer for analyzing large xmldom.

As a general read-only operation, the node is accessed sequentially using ordinary XML reader. The difference is that you can use XML writer to change the value of the attribute and the contents of the node while you are reading it. You use reader to read each node in the source file, and writer in the background creates a copy of the node. In this copy, you can add new nodes, ignore or edit other nodes, and edit the values of the properties. When you have completed the changes, you will replace the old document with the new one.

A simple and effective way is to copy the node object into the write stream from the read-only stream, which can be used in the two methods in the XmlTextWriter class: The WriteAttributes method and the WriteNode method. The WriteAttributes method reads all valid properties for the selected node in the current reader, and then copies the attribute as a separate string into the current output stream. Similarly, the WriteNode method handles other types of nodes except the attribute nodes in a similar way. The code snippet shown in Figure 10 demonstrates how to create a copy of a source XML document using the above two methods, optionally modifying some nodes. The XML tree is accessed from the root, but only nodes of a type other than the attribute node type are exported. You can integrate reader and writer into a new class, design a new interface that allows it to read and write streams and access properties and nodes.

Figure 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 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 did not inherit from the XmlReader or XmlWriter class. Instead, there are two other classes, one based on the read-only stream (stream), and the other based on the write-only flow of an action class. The Xmltextreadwriter class method reads the data with the reader object and writes to the writer object. In order to adapt to different requirements, the internal reader and writer objects are exposed by read-only reader and writer attributes respectively. Figure 11 lists some of the methods for this class:

Figure Xmltextreadwriter Class Methods

Method
Description

Addattributechange
Caches all of the information needed to perform a is on a node attribute. All the changes cached through is 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.


The new class has a Read method, which is a simple encapsulation of the Read method of reader. In addition, it provides the writerstartdocument and WriteEndDocument methods. They initialize/release (finalize) the internal reader and writer objects, and also handle all I/O operations. As we iterate over the nodes, we can modify the nodes directly. For performance reasons, the attribute must be declared with the Addattributechange method before it can be modified. All modifications made to a node's properties are stored in a temporary table, and finally, by invoking the WriteAttribute method, the temporary table is purged.

The code shown in Figure 12 demonstrates the advantage of the client using the Xmltextreadwriter class to modify property values while reading. C # and VB source code downloads for the Xmltextreadwriter class are available in MSDN in this issue (see the link provided at the beginning of this article).
Figure 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 modifying the root node

rw. Writer.writestartelement (rw. Reader.localname);

Start modifying properties

(You can modify the properties of more nodes)

rw. Addattributechange (NodeName, Attribname, Oldval, newval);

Looping through documents

while (RW. Read ())

{

Switch (rw. NodeType)

{

Case XmlNodeType.Element:

rw. Writer.writestartelement (rw. Reader.localname);

if (nodename = rw. Reader.localname)

modifying properties

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

rw. WriteEndDocument ();

}

The xmltextreadwriter class can not only read XML documents, but also write XML documents. You can read the contents of an XML document and use it to do some basic updates if you need to. The basic update operation here is to modify the value of an existing property or the contents of a node, or to add a new attribute or node. For more complex operations, it is best to use the XMLDOM Analyzer.

Summary

reader and writer are fundamental to processing XML data in the. NET framework. They provide the raw API for all XML data access capabilities. Reader is like a new parser class that has the power of xmldom and the quick simplicity of sax. Writer is designed for simple creation of XML documents. Although both reader and writer are a small piece of the. NET framework, they are separate APIs. In this article, we only discuss how to do some major work with reader and writer, introduce the principle mechanism of validating analyzer, and integrate reader and writer into a separate class. All of these classes are lightweight, similar to the cursor-type XMLDOM parser. (Chyich translation/aspcool)



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.