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 Introduction: 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 of the namespaces related to XML technology and some of them. 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 of reading an XML document: After introducing the Net Framework and XML and the related category, I will then introduce some of the information 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 an object class and calls XmlTextReader Read method to read the file XmlTextReader textReader = new XmlTextReader ( "C: / /books.xml "); TextReader.read (); // Node Non-air defense Performs a cyclic 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:" TextReader.Name "; console.writeline (" Base Uri: " TextReader.baseuri); Console.writeline (" local name: " TextReader.localName); console.writeline (" Attribute Count: " TextReader.attributeCount.Tostring ()); console.writeline ("defth:" textReader.Depth.tostring ()); console.writeline ("Line Number:" TextReader.LineNumber.tostring ()); console.writeline "Node Type:" TextReader.NodeType.toString ()); "Attribute Count:" TextReader.Value.tostring ());}}}} XmlTextReader class has a very important property -NodetyPE, With this property, 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; use 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 ET = 0; int = 0; XMLTextReader textReader = new XMLTextReader ("c: //books.xml"); while (TextReader.Read ()) {xmlnodetype ntype = textReader.nodeType; // Node Type Xmldeclaration if (ntype == xmlnodetype.xmldeclaration) {Console.writeline ("Declaration:" TextReader.name.tostring ()); xd = xd 1;} // node type commentiff (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 ()); ET = ET 1 } / / Node type Process Instruction if (nType == XmlNodeType ProcessInstruction.) {Console.WriteLine ( "Process Instruction:" textReader.Name.ToString ()); pi = pi 1;} // node type DocumentType if ( nType == XmlNodeType.DocumentType) {Console.WriteLine ( "DocumentType:" textReader.Name.ToString ()); dc = dc 1;} // node type 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 ()); console.writeline ("Total Attributes:" ac.tostring ()); console.writeline ("Total Elements:" El.Tostring ()); Console.Writeline ("Total Entity:" et.tostring ()); console.writeline ("Total Process Instructions:" Pi.toString ()); Console .Writeline ("Total Declaration:" xd.to.writeline ("Total DocumentType: DC.TOString ()); Console.Writeline (" Total Whitespaces: " ws.toString ()); }}} The above, I introduced you 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 an XML document: 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 class XmlTextWriter textWriter XmlTextWriter = new XmlTextWriter ( "C: //myXmFile.xml", null) ; // start the writing process, calls WriteStartDocument method textWriter.WriteStartDocument (); // write notes textWriter.WriteComment ( "First Comment XmlTextWriter Sample Example"); textWriter.WriteComment ( "myXmlFile.xml in root dir"); // Write an element TextWriter.WriteStartElement ("Name", "); TextWriter.writestring (" student "); TextWriter.WriteEndelement (); // Written again to 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.WritStartElement ("char"); TextWriter.WriteChars (ch, 0, ch.length); textwriter.writeEndelement (); // End, call WriteEndDocument method Textwriter.writeEndDocument () ; // Turn off textwriter textwriter.close ();}}}. Using the XMLDocument class: The object of 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 (("