Parsing XML programming technology under the. NET Framework
I. Preface:
XML is an important part of Microsoft's. NET strategy, and it is the cornerstone of XML Web Services. Therefore, it is very important to master the XML technology under the. NET Framework. This document describes how to use the C # language to read and write XML documents under the. NET Framework. First, I will introduce the XML-related namespaces and important classes in the. NET Framework. Next, I will give examples to help readers better understand the specific methods for reading and writing XML documents.
II. Introduction to XML Namespaces and related classes:
Before proceeding to the XML document operations under the. NET Framework, I think it is necessary to introduce the namespaces related to the XML technology and some important classes in the. NET Framework .. The. NET Framework provides the following namespaces: system. XML, system. XML. schema, system. XML. serialization, system. XML. XPath and system. XML. XSL to include classes related to XML operations.
-The system. xml namespace contains some of the most important XML classes. The most important class is related to the read/write operations of XML documents. These classes include four read-related classes and two write-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 important classes.
-The xmlreader class is a virtual base class that contains methods and attributes for reading XML documents. The read method in this class is a basic method for reading XML documents. It reads nodes in XML documents as streams ). This class also provides more advanced read methods such as readstring, readinnerxml, readouterxml, and readstartelement. In addition to reading XML documents, the xmlreader class also provides programmers with navigation functions such as movetoattribute, movetofirstattricontent, movetocontent, movetofirstcontent, movetoelement, and movetonextattribute. In the examples described later in this article, we will apply these methods.
-Xmltextreader, xmlnodereader, xmlvalidatingreader, and other classes are inherited from the xmlreader class. Based on their names, we can know that they are used to read text content, read nodes, and read XML Schema (Schemas ).
-The xmlwriter class provides a lot of methods for programmers to write XML documents. It is the base class of the xmltextwriter class. I will provide relevant usage methods in the following examples.
-The xmlnode class is a very important class, which represents a node in the XML document. This node can be the root node of the XML document, which represents the entire XML document. It is the base class of many useful classes, including the class for inserting nodes, deleting nodes, replacing nodes, and completing navigation in XML documents. At the same time, the xmlnode class also provides the programmer with attributes such as the parent node, child node, last child node, node name, and node type. Its three main subclasses include xmldocument, xmldatadocument, and xmldocumentfragment. The xmldocument class represents an XML document. It provides methods and attributes for loading and saving XML documents. These methods include load, loadxml, and save. It also provides the ability to add XML items such as attributes, comments, spaces, elements, and new nodes. The xmldocumentfragment class represents a part of XML documents that can be added to other XML documents. The xmldatadocument class allows programmers to better interoperate with dataset objects in ADO. net.
In addition to the system. in addition to the classes in the XML namespace, The namespace also includes classes such as xmlconvert, xml1_node, and xmlnodelist. However, these classes are not the focus of this article, interested readers may wish to refer to the relevant documentation.
The system. xml. schema namespace contains classes related to the XML schema, including XMLSCHEMA, xmlschemaall, xmlschemaxpath, and xmlschematype.
System. XML. the serialization namespace contains classes related to the serialization and deserialization operations of XML documents, the serialization operation of XML documents can convert XML format data into Stream format data and transmit it in the network, while deserialization completes the opposite operation, restores data in stream format to XML format.
The system. xml. XPath namespace contains xpathdocument, xpathexression, xpathnavigator, xpathnodeiterator, and other classes that can complete the navigation of XML documents. With the help of the xpathdocument class, the xpathnavigator class can complete the quick XML document navigation function, which provides programmers with many move methods to complete the navigation function. The class in the system. xml. XSL namespace completes the XSLT conversion function.
Iii. Methods for reading XML documents:
After introducing the XML-related namespaces and classes in the. NET Framework, I will introduce some XML-related operations to you. First, I will introduce you to the method for reading XML documents. In the following instance program, I will use the "books. xml" file attached to the vs.net development tool as an example. You can search for this file on your machine (or refer to the appendix), or you can use other XML files.
First, we use the object of the xmltextreader class to read the XML document. The method is simple, that is, to specify the location of the XML file 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 the read method is called, the information is stored. You can obtain the information by reading the attributes of the object, such as name, baseuri, depth, and linenumber. Next, I will provide a complete example. The instance simply reads the "books. xml" file and displays the information in the console.
Using system;
Using system. xml;
Namespace readxml
{
Class class1
{
Static void main (string [] ARGs)
{
// Create an xmltextreader Class Object and call the read method to read the object
Xmltextreader textreader = new xmltextreader ("C: // books. xml ");
Textreader. Read ();
// Execute the loop body if the node is not empty
While (textreader. Read ())
{
// Read the first element
Textreader. movetoelement ();
Console. writeline ("xmltextreader Properties Test ");
Console. writeline ("========================= ");
// Read the attributes of the element and display it on the console
Console. writeline ("name:" + textreader. Name );
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 ());
}
}
}
}
The xmltextreader class has a very important attribute-nodetype. Through this attribute, we can know the node type of the node. The enumerated type xmlnodetype contains XML items such as attribute, CDATA, element, comment, document, documenttype, entity, processinstruction, and whitespace. By comparing with the element in xmlnodetype, we can obtain the node type of the corresponding node and perform related operations on it. Next I will provide an instance that reads the nodetype of each node and displays its content based on the node type. 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 ET = 0;
Int El = 0;
Int XD = 0;
Xmltextreader textreader = new xmltextreader ("C: // books. xml ");
While (textreader. Read ())
{
Xmlnodetype ntype = textreader. nodetype;
// The node type is xmldeclaration.
If (ntype = xmlnodetype. xmldeclaration)
{
Console. writeline ("Declaration:" + textreader. Name. tostring ());
XD = XD + 1;
}
// The node type is comment.
If (ntype = xmlnodetype. Comment)
{
Console. writeline ("comment:" + textreader. Name. tostring ());
Cc = CC + 1;
}
// The node type is attribute.
If (ntype = xmlnodetype. Attribute)
{
Console. writeline ("attribute:" + textreader. Name. tostring ());
AC = AC + 1;
}
// The node type is element.
If (ntype = xmlnodetype. element)
{
Console. writeline ("element:" + textreader. Name. tostring ());
El = EL + 1;
}
// The node type is entity.
If (ntype = xmlnodetype. entity)
{
Console. writeline ("entity:" + textreader. Name. tostring ());
ET = ET + 1;
}
// The node type is process instruction.
If (ntype = xmlnodetype. processinstruction)
{
Console. writeline ("process instruction:" + textreader. Name. tostring ());
Pi = PI + 1;
}
// The node type is documenttype.
If (ntype = xmlnodetype. documenttype)
{
Console. writeline ("documenttype:" + textreader. Name. tostring ());
Dc = DC + 1;
}
// The node type is whitespace.
If (ntype = xmlnodetype. whitespace)
{
Console. writeline ("whitespace:" + textreader. Name. tostring ());
Ws = ws + 1;
}
}
// Display 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. tostring ());
Console. writeline ("Total documenttype:" + DC. tostring ());
Console. writeline ("Total whitespaces:" + WS. tostring ());
}
}
}
The above section describes how to use the xmltextreader class object to read the XML document and obtain the node type information based on the node's nodetype attribute. At the same time, xmlreader is a base class, including xmlnodereader and xmlvalidatingreader. They are used to read the nodes and modes of XML documents. This article will not be introduced here. Readers can refer to the relevant materials.
4. Method for writing XML documents:
The xmlwriter class contains the methods and attributes required for writing XML documents. It is the base class of the xmltextwriter class and xmlnodewriter class. This class contains writenode, writestring, writeattributes, writestartelement, writeendelement, and other methods for writing XML documents. Some of these methods are paired. For example, to write an element, you must first call the writestartelement method, then write the actual content, and finally call the writeendelement method to end the operation. This class also contains attributes such as writestate, xmllang, and xmlspace. The writestate attribute indicates the write status. Because the xmlwriter class contains a lot of methods for writing XML documents, we will introduce the most important methods here. The following describes how to write an XML document through the xmltextwriter class.
First, create an Instance Object of the xmltextwriter class. The constructor xmltextwriter of this class has three reloads. Its parameters are a string, a stream object, and a textwriter object. Here we use the string parameter form to specify 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 write the XML document. After the write is completed, we call writeenddocument to end the write process and call the close method to close the object. During the write process, we can call the writecomment method to add instructions, call the writestring method to add a string, and call the writestartelement and writeendelement methods to add an element, you can call the writestartattribute and writeendattribute methods to add an attribute. We can also call the writenode method to add an entire node. Other Write methods include writeprocessinginstruction and writedoctype. The following example describes how to use these methods to write XML documents.
Using system;
Using system. xml;
Namespace writexml
{
Class class1
{
Static void main (string [] ARGs)
{
// Create an Instance Object of the xmltextwriter class
Xmltextwriter textwriter = new xmltextwriter ("C: // myxmfile. xml", null );
// Start the write process and call the writestartdocument Method
Textwriter. writestartdocument ();
// Write description
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 ();
// Write another element
Textwriter. writestartelement ("Address ","");
Textwriter. writestring ("colony ");
Textwriter. writeendelement ();
// Write characters
Char [] CH = new char [3];
Ch [0] = 'a ';
Ch [1] = 'R ';
Ch [2] = 'C ';
Textwriter. writestartelement ("char ");
Textwriter. writechars (CH, 0, Ch. Length );
Textwriter. writeendelement ();
// When the document writing ends, call the writeenddocument method.
Textwriter. writeenddocument ();
// Disable textwriter
Textwriter. Close ();
}
}
}
5. Use the xmldocument class:
The object of the xmldocument class represents an XML document, which is also a very important XML class. This class contains load, loadxml, save, and other important methods. The load method can import XML data from an XML file specified by a string, a stream object, a textreader object, and an xmlreader object. The loadxml method imports XML data from a specific XML file. The Save method saves the XML data to an XML file, a stream object, a textwriter object, and an xmlwriter object.
The loadxml method of the xmldocument class object is used in the following program. It reads XML data from an XML document segment and calls its save method to save the data in a file.
// Create an object of the xmldocument class
Xmldocument Doc = new xmldocument ();
Doc. loadxml ("<student type = 'regular' section = 'B'> <Name> Tommy Lex </Name> </student> "));
// Save it to the file
Doc. Save ("C: // student. xml ");
Here, we can also display XML data in the console by changing the parameters in the SAVE method. The method is as follows:
Doc. Save (console. Out );
In the following program, we use an xmltextreader object to read the XML data in the "books. xml" file. Create an xmldocument object and load the xmltextreader object, so that the XML data is read to the xmldocument object. Finally, the XML data is displayed on the console using the Save method of the object.
Xmldocument Doc = new xmldocument ();
// Create an xmltextreader object to read XML data
Xmltextreader reader = new xmltextreader ("C: // books. xml ");
Reader. Read ();
// Load the object of the xmltextreader class
Doc. Load (Reader );
// Display XML data in the console
Doc. Save (console. Out );
6. Summary:
XML technology, as the cornerstone of. net, is naturally important .. The. NET Framework contains five namespaces and a large number of classes to support XML-related operations. Among them, system. XML is the most important namespace. The xmlreader class, xmlwriter class, and Their Derived classes complete the read and write operations on XML documents, which is the most basic and important class. The xmldocument class represents an XML document. It can complete all types of operations related to the entire XML document, and its xmldatadocument class is also very important and worthy of further research.
Appendix: The "books. xml" file is as follows:
<? XML version = '1. 0'?>
<! -- This file represents a fragment of a book store inventory database -->
<Bookstore>
<Book genre = "autobiography" publicationdate = "1981" ISBN = "1-861003-11-0">
<Title> The Autobiography of Benjamin Franklin </title>
<Author>
<First-name> Benjamin </first-name>
<Last-name> Franklin </last-name>
</Author>
<Price> 8.99 </price>
</Book>
<Book genre = "novel" publicationdate = "1967" ISBN = "0-201-63361-2">
<Title> the confidence man </title>
<Author>
<First-name> Herman </first-name>
<Last-name> Melville </last-name>
</Author>
<Price> 11.99 </price>
</Book>
<Book genre = "Philosophy" publicationdate = "1991" ISBN = "1-861001-57-6">
<Title> the gorgias </title>
<Author>
<First-name> Sidas </first-name>
<Last-name> Plato </last-name>
</Author>
<Price> 9.99 </price>
</Book>
</Bookstore>
Related Articles:
- Parsing XML Programming Technology in the. NET Framework jabby12
- Parsing XML programming technology under the. NET Framework (ii) hb226
- Analysis of XML Programming Technology in the. NET Framework 2006-04-17 qdzx2008
- Read XML file content Eleda
- Easily process XML data in. NET Framework...