XML programming techniques of analytical .Net framework under: Shanghai Wang Kaiming a. 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 will guide
How do you use 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. Secondly,
I 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. .NET framework
To provide us with some of the namespaces: system.xml, system.xml.schema, system.xml.serialization, system.xml.xpath, and system.xml.xsl
Accessories related to XML operations.
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 related classes and 2
Write related classes. They are: XmlReader, XmlTextReader, XmlValidatingReader, XMLNodeReader, XMLWriter, and XMLTextWriter. This article will focus
These classes are introduced 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 the XML document, which reads the XML document in a flow form.
Node (Node). In addition, this class also provides more advanced reading methods such as ReadString, ReadinnerXML, ReadouterXML, and ReadStartElement. In addition to providing reading XML documents
In addition, the XMLReader class also provides programmers with MoveToAttribute, MoveTofirst, MoveTofirstcontent, MoveToElement.
And MovetoneXTAttribute, etc. have navigation features. In the examples described later, we will use these methods.
XMLTextReader, XMLNodeReader, and XMLValidatingReader, etc. are subclasses inherited from the XMLReader class. According to their name, we can know its role
It is 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 lot of very
The base class of useful classes, these classes include classes inserted nodes, delete nodes, replace nodes, and classes that complete navigation functions in XML documents. At the same time, the XMLNode class is also programmers
Provides attributes for obtaining a dual-pro-node, child node, last child node, node name, and node type. 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, etc. 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. XMLDATADOCUMENT class can
Let the programmer better completed interoperability between data set 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 categories are not this article.
The focus of the introduction, interested readers may wish to refer to the relevant documentation.
System.xml.schema namespace contains classes related to XML mode, including Xmlschema, XmlschemaAll, XmlschemaxPath, and Xmlschematype.
System.xml.Serialization Namespace contains the serialization of the XML document and the deserialization operation related class, the serialization operation of the XML document can convert the data of the XML format into streams.
The formatted data and can be transmitted in the network, and the reverse sequence is completed, the flow format is reduced to the data of the XML format.
System.xml.xPath namespace contains XpathDocument, XPATHEXRESSION, XPATHNAVIGATOR, and XPathNodeTeiterator, etc., which can complete the XML document
Availability. 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 to complete navigation features.
.
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 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 read the Name of the object,
Baseuri, depth, linenumber and other attributes get this information. Below I give a complete example, the instance reads the "books.xml" file simple, then the letter
The interest is 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 ("======================================================================================================================================================================================================00 ); Console.WriteLine ( "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.toString ()); 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 XMLNodetyPE contains such as
Type of XML items such as Attribute, CData, Element, Comment, Document, DocumentType, Entity, Processinstruction, and WHITESPACE. Pass
Comparison of elements in XMLNodetyPE, we can get the node type of the corresponding node and complete the relevant operations. Let's give an example, this instance reads each node
NodeType, and display 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 XmlDeclarationif (nType == XmlNodeType.XmlDeclaration) {Console.WriteLine ( "Declaration:" textReader.Name.ToString ()); xd = XD 1;}
// node type is Commentif (ntype == xmlnodetype.com "{console.writeLine (" comment: " textReader.name.toT7tring ()); cc = cc 1;}
// node type is attributeif (ntype == xmlnodetype.attribute) {Console.writeline ("Attribute:" TextReader.name.tostring ()); AC = AC 1;}
// node type is elementif (ntype == xmlnodetype.Element) {console.writeline ("Element:" TextReader.name.tostring ()); EL = EL 1;}
// node type is entityif (ntype == xmlnodetype.entity) {console.writeline ("Entity:" TextReader.name.tostring ()); et = et 1;}
// node type is Process INSTRUCTIONIF (NTYPE == XMLNodeType. Processinstruction) {Console.Writeline ("Process Instruction:" TextReader.name.toString ()); PI = Pi 1;}
// node type is DocumentTypeif (ntype == xmlnodetype.documenttype) {console.writeline ("DocumentType:" TextReader.name.tostring ()); DC = DC 1;}
// Node type is whitespaceif (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. XMLReader
There are also XMLNodeReader and XMLValidatingReader, which are used to read the nodes and patterns of the XML document. Limited to the space, this is not introduced, readers
You 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 WriteEndelement methods such as write XML documents, some methods are pairs. For example, you have to write an element
You first have to call the WriteStartElement method, then write the actual content, and finally call the WriteEndelement method to indicate the end. This class also contains WriteState,
XMLLANG and XMLSpace and other properties, where the WriteState property indicates the state of writing. Because the XMLWRITER class contains a lot of ways to write XML documents, it is only the main introduction.
Several. 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, and the parameters are one 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 creating the object, we call the WriterStartDocument method to start writing XML documents. After completing the write work, call the WriteEndDocument to end the write process and call the Close method.
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, by calling
WriteStartElement and WriteEndelement methods add an element to add an attribute by calling 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
That is to show 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 off textWritertextWriter.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 XML data in an XML file or a stream object specified from a string, a TextReader object, an XMLReader object. LoadXML method completes from a specific XML
The file is imported into the function of XML data. 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 (("
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 in parallel
Enter the XMLTextReader object, so XML data is read to 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 the XML document, which can complete all kinds of operations related to the entire XML document, and the related XMLDATADOCUMENT class is also very important, it is worth the reader's deep
Investigate.
appendix
The "boxs.xml" file is as follows: