Analysis of XML programming technology under the .NET framework

xiaoxiao2021-03-06  92

One. Preface:

XML is an important part of Microsoft .NET strategy, and it is the cornerstone of the XML web service, so the XML technology under the .NET framework is naturally very important. This article uses the C # language to complete the read and write operations of the XML document under the .NET framework. First, I will introduce you to the .NET framework and the XML-related namespace and important classes. Second, I will also give the relevant examples to make the reader further understand the specific method of reading and writing of the XML document.

two. XML namespace and related class profiles:

Before the operation of the XML document under the .NET framework, I think it is necessary to introduce you to the .NET framework and some important classes related to XML technology. The .NET framework provides us with some of the following namespaces: system.xml, system.xml.schema, system.xml.serialization, system.xml.xpath, and system.xml.xsl to inclose and XML operations related classes.

System.xml Namespace contains some of the most important XML classes, where the most important class is class related to the read and write operations of the XML document. These classes include four classes related to read-related classes and 2 related classes. They are: XmlReader, XmlTextReader, XmlValidatingReader, XMLNodeReader, XMLWriter, and XMLTextWriter. This article will focus on these classes because they are the most basic and most important classes.

The XMLReader class is a virtual base class that contains methods and properties of reading an XML document. The Read method in this class is a basic way to read an XML document, which reads the node (Node) in the XML document in a flow form. In addition, this class also provides more advanced reading methods such as ReadString, ReadinnerXML, ReadouterXML, and ReadStartElement. In addition to providing a method of reading an XML document, the XMLReader class provides programmers with navigation features such as MoveToAttribute, MoveToContent, MoveTofirstContent, MoveToContent, and MoveTONEXTATTRIBUTE. In the examples described later, we will use these methods.

XMLTextReader, XMLNodeReader, and XMLValidatingReader, etc. are subclasses inherited from the XMLReader class. Based on their name, we can know that its role is to read text content, read nodes, and read XML mode (Schemas).

The XMLWRITER class provides programmers with a number of ways to write an XML document. It is the base class of the XMLTextWriter class. I will give relevant method of utilization in the following instance.

The XMLNode class is a very important class that represents a node in the XML document. The node can be the root node of an XML document, which represents the entire XML document. It is a basic class of many useful classes, including the classes of the plug, delete nodes, and classes of the node, and classes that complete the navigation function in the XML document. At the same time, the XMLNode class also provides programmers with attributes that get dual-pro-nodes, child nodes, last child nodes, node names, and node types. Its three most primary subclasses include: XMLDocument, XmLDATADOCUMENT, and XMLDocumentFragment. The XMLDocument class represents an XML document that provides methods and properties that load and save an XML document. These methods include LOAD, LOADXML, and SAVE, and the like. At the same time, it also provides the functionality of adding features (Attributes), Spaces, Spaces, Elements, and New Nodes, and other XML items. The XMLDocumentFragment class represents a part of the XML documentation that can be used to add to another XML document. The XMLDATADOCUMENT class allows programmers to better complete interoperability between dataset objects in ADO.NET. In addition to the categories in the System.xml namespace described above, the namespace also includes XmlConvert, XMllinkedNode, and XMLNodelist, but these classes are not the focus of this article. Interested readers may wish to refer to relevant documentation.

System.xml.schema namespace contains classes related to XML mode, including Xmlschema, XmlschemaAll, XmlschemaxPath, and Xmlschematype.

System.xml.Serialization Namespace contains serialization and reverse sequenced operations related to XML documents, and the serialization operation of the XML document converts the data of the XML format into stream format and can be transmitted in the network. The reverse sequence is completed, and the flow format is reduced to data in XML format.

System.xml.xPath namespace contains XpathDocument, XPATHEXRESSION, XPATHNAVIGATOR, and XPathNodeTeiterator, etc., which can complete the navigation function of the XML document. With the assistance of the XPathDocument class, the XPathnavigator class can complete the fast XML document navigation function, which provides a number of MOVE methods for programmers to complete navigation.

The class in the system.xml.xsl namespace completes the XSLT conversion function.

three. Method for reading an XML document:

After introducing the .NET framework and XML related namespace and related classes, I will then introduce some of the operations related to XML. First, I will introduce you to the way to read the XML document. In the example program below, I will use the "Books.xml" file with the vs.net development tool as an example. You can search for this file (or please refer to Appendix) on your machine, or you can also use other XML files.

First, we read the XML document with an object of the XMLTextReader class. The method is simple, that is, the location of the XML file is indicated in the constructor of the new object.

XmlTextReader textReader = New XMLTextReader ("C: //Books.xml");

Once the new object is created, you can call its read method to read the XML document. After calling the read method, the information is stored, you can get this information by reading attributes such as Name, BaseURI, Depth, LineNumber, etc. Below I give a complete example, the instance reads the "books.xml" file simple, then displayed in the console. Using system; using system.xml;

namespace ReadXml {class Class1 {static void Main (string [] args) {// create a XmlTextReader object class and calls the Read method to read the file XmlTextReader textReader = new XmlTextReader ( "C: //books.xml"); textReader .Read (); // node non-air defense execution cycle body while (TextReader.Read ()) {// reads the first element TextReader.movetoElement (); console.writeLine ("XmlTextReader Properties Test"; console. WriteLine ("=====================");

/ / Read the properties of this element and display console.writeline in the console ("Name:"; "Base Uri:" TextReader.Baseuri; Console.Writeline ("Local Name: " textReader.LocalName); Console.WriteLine (" Attribute Count: " textReader.AttributeCount.ToString ()); Console.WriteLine (" Depth: " textReader.Depth.ToString ()); Console.WriteLine (" Line Number: " TEXTREADER.LINENUMBER.TOSTRING ()); console.writeline (" Node Type: " TextReader.NodeType.toTRING ()); console.writeline (" Attribute Count: " TextReader.Value.toString ()) }}}}}

There is a very important property-NodeType in the XMLTextReader class. We can know the node type of its nodes. The enumerated type XMLNodType includes Type of XML items such as Attribute, CData, Element, Comment, Document, DocumentType, Entity, Processinstruction, and Whitespace. By comparing with elements in XMLNodType, we can get the node type of the corresponding node and complete the relevant operations. Let me give an instance that the instance reads the NodeType of each node and displays the content according to its node type, and the program also records the number of each node type in the XML file.

Using system; using system.xml;

Namespace readxml {class class2 {static void main (string [] args) {int ws = 0; int pi = 0; int DC = 0; int CC = 0; int AC = 0; int = 0; int EL = 0 ; int xd = 0; XMLTextReader textReader = New XMLTextReader ("C: //Books.xml");

While (TextReader.Read ()) {xmlnodetype ntype = textreader.nodetype;

// node type is xmldeclarative if (ntype == xmlnodetype.xmldeclaration) {console.writeline ("declaration:" TextReader.name.tostring ()); xd = xd 1;}

// Node type is Comment if (ntype == xmlnodetype.comment) {Console.Writeline ("Comment:" TextReader.name.toString ()); cc = cc 1;}

// Node type is attribute if (ntype == xmlnodetype.attribute) {console.writeline ("Attribute:" TextReader.name.toTString ()); ac = AC 1;}

// node type is element if (ntype == xmlnodetype.ement) {console.writeline ("Element:" TextReader.name.tostring ()); EL = EL 1;}

// node type is Entity if (ntype == xmlnodetype.entity) {console.writeline ("Entity:" TextReader.name.tostring ()); etc = etc 1;}

// node type is Process IF (NTYPE == XMLNodType. Processinstruction) {Console.writeline ("Process Instruction:" TextReader.name.tostring ()); pi = pi 1;}

// node type is DocumentType if (ntype == xmlnodetype.documenttype) {Console.Writeline ("DocumentType:" TextReader.name.toString ()); DC = DC 1;}

// node type is whitespace if (ntype == xmlnodetype.whitespace) {Console.writeline ("Whitespace:" TextReader.name.tostring ()); ws = ws 1;}}

// Show the number of each type in the console Console.Writeline ("Total Comments:" cc.tostring ()); "Total Attributes:" ac.toLestring ()); console.writeline Total Elements: " el.tostring ()); console.writeline (" Total Entity: " et.tostring ()); console.writeline (" Total Process Instructions: " Pi.toTString ()); console.writeline ("Total Declaration:" Xd.toString ()); console.writeline ("Total DocumentType:" DC.TOString ()); console.writeline ("Total Whitespaces:" ws.tostring ());}} } The above, I introduced you to how to use the XMLTextReader class to read the XML document and obtain its node type information based on the nodetype property of the node. At the same time, XMLReader has the base class of XMLNodeReader and XMLValidatingReader, which are used to read the nodes and patterns of the XML document. Limited to the space, this will not be introduced, the reader can refer to the relevant information.

four. Write XML documents:

The XMLWRITER class contains the methods and properties required to write XML documents, which is the base class of the XMLTextWriter class and the XMLNodeWriter class. This class contains WriteNode, WriteString, WriteAttributes, WriteStartElement, and WriteEndeEndelement methods such as write XML documents, some methods are pairs. For example, if you want to write an element, you must first call the WriteStartElement method, then write the actual content, and finally call the WriteEndelement method to indicate the end. This class also includes attributes such as WriteState, Xmllang, and XMLspace, where the WriteState property indicates the state of writing. Because the XMLWRITER class contains many ways to write XML documents, this is just a few more. Below we describe how to write an XML document through its subclass XMLTextWriter class.

First, we have to create an instance object of an XMLTextWriter class. The constructor XMLTextWriter of this class has three overloaded forms, which are a string, a stream object, and a TextWriter object. Here we use the parameters of the string, which indicates the location of the XML file to be created, the method is as follows:

XmlTextWriter TextWriter = New XmlTextWriter ("C: //Myxmfile.xml", NULL);

After the object is created, we call the WriterStartDocument method to start writing an XML document. After completing the write work, call the WriteEndDocument to end the write process and call the Close method to close it. In the process of writing, we can call the WriteComment method to add a description, add a string by calling the WritestRing method, add an element to the WriteStartEndeEndelement method, add an attribute by calling the WriteStartAttribute and WriteEndAttribute method. We can also add the entire node by calling the Writenode method, and other write methods include WriteProcessinginstruction and WriteDOCTYPE, and more. The following example is to describe how to use these methods to complete the write work of the XML document. Using system; using system.xml;

Namespace WriteXml {class class1 {static void main (string [] args) {// Create an instance of the XMLTextWriter class XMLTextWriter TextWriter = New XmlTextWriter ("C: //Myxmfile.xml", NULL);

/ / Start writing process, call WriteStartDocument method textwriter.writestartDocument ();

// Write a description TextWriter.WriteComment ("FirstWomment XmlTextWriter Sample"); TextWriter.WriteComment ("MyXMLFile.xml in root dir");

// Write an element TextWriter.writestartElement ("Name", "); TextWriter.WritString (" student "); textwriter.writeEndelement ();

// Reclusion an element TEXTWRITER.WRITESTARTELEMENT ("Address", ""; TextWriter.writestring ("Colony"); TextWriter.writeEndelement ();

// Write character char [] ch = new char [3]; ch [0] = 'a'; CH [1] = 'r'; ch [2] = 'c'; TextWriter.writestrtlement ("char" ); TextWriter.writechars (ch, 0, ch.length); textwriter.writeEndelement ();

// The end of the write document, call WriteEndDocument method textwriter.writeEndDocument ();

// Turn the textwriter textwriter.close ();}}}}}}}

Fives. Use the XMLDocument class:

The XMLDocument class represents an XML document, which is also a very important XML class. This class contains important methods such as LOAD, LOADXML, and SAVE. Where the LOAD method can import an XML data from an XML file or a stream object specified from a string, a TextReader object, an XMLReader object. The LOADXML method completes the ability to import XML data from a specific XML file. Its Save method saves XML data to an XML file or a stream object, a TextWriter object, an XMLWRITER object. In the following program we use the loadXML method of the XMLDocument class object, which reads XML data from an XML document segment and calls its Save method to save the data in a file.

// Create an object xmldocument doc = new xmldocument (); doc.loadxml ((" Tommy lex ) );

/ / Save to Doc.save ("C: //student.xml") in the file;

Here, we can also display XML data in the console by changing the parameters in the Save method, and the methods are as follows:

Doc.save (console.out);

In the following program, we use an XMLTextReader object, and we read the XML data in the "books.xml" file. Then create an XMLDocument object and load the XMLTextReader object so that XML data is read in the XMLDocument object. Finally, the XML data is displayed in the console through the SAVE method of the object.

XMLDocument doc = new xmlDocument (); // Create an XMLTextReader object, read XML data XMLTextReader Reader = New XMLTextReader ("C: //Books.xml"); reader.read ();

// Load the object doc.load (reader) of the XMLTextReader class; // Displayed XML data in the console Doc.Save (console.out);

six. to sum up:

XML technology as the cornerstone of .NET, its importance is naturally self-evident. The .NET framework contains five namespaces and a large number of classes to support operations related to XML technology. System.xml is the most important namespace, the XMLReader class and the XMLWRITER class, and their derived classes complete the read and write operations of the XML document, is the most basic and most important class. The XMLDocument class represents an XML document that can complete all kinds of operations associated with the entire XML document, and the related XMLDATADOCUMENT class is also very important, it is worthy of in-depth research.

appendix

The "boxs.xml" file is as follows:

转载请注明原文地址:https://www.9cbs.com/read-95672.html

New Post(0)