C # Analysis on reading XML documents using XMLTextReader class

Source: Internet
Author: User

C # How to compare the two methods of reading XML documents? Let's first take a look at the comparison between XMLTextReader and XmlDocument reading XML files:

C # Read the XML document. The XMLTextReader class contained in the System. XML namespace Of the. NET Framework can quickly read data from XML files without having to have high requirements on System resources. The XMLTextReader class can be used to read data from an XML file and convert it to HTML format for output in a browser.

Before reading this article, you need to know some basic knowledge: XML, HTML, C # programming language, and some knowledge about. NET, especially ASP. NET frameworks.

C # For the purpose of reading XML documents, Microsoft's. the NET Framework provides developers with a lot of development convenience. As XML becomes increasingly important, developers are looking forward to developing a complete set of powerful XML tools .. The. NET Framework has failed to meet our expectations. In the System. XML namespace, the following classes are organized for XML:

XMLTextReader ------ provides quick, unidirectional, and unbuffered access to XML data. (One-way reading means you can only read XML files from the past, but not reverse reading)

XMLValidatingReader ------ used with the XMLTextReader class to verify the DTD, XDR, and XSD architectures.

XMLDocument ------ follows the level 1 and level 2 standards of W3C Document Object Model specifications to achieve random and cache access to XML data. The level-1 level includes the most basic part of the DOM, while the level-2 level has added a variety of improvements, including added support for namespace and level-2 link charts (CSS.

XMLTextWriter ------ generate XML files that comply with W3C XML 1.0 specifications.

The C # method described in this article to read XML documents is the first XMLTextReader class, which is designed to quickly read data from XML files, however, there is no high requirement on system resources (mainly including memory and processor time. Under the control of the parent program, it gradually operates the XML file by processing only one node at a time to implement this kind of work process. In each node of the XML file, the parent program determines the node type, its attributes and data (if any), and other information about the node. Based on this information, the parent program can choose whether to process the node or ignore the node information to meet the needs of various application requests. This is called a pull processing model, because the parent program sends a request and extracts nodes from the XML file, and then processes it as needed or does not process it.

We can compare the XMLTextReader class with the simple XML application interface, that is, the SAX, which is another popular technology for programmers to read XML data. XMLTextReader and SAX are similar in that they can quickly read data from XML files without occupying a lot of system resources. However, unlike XMLTextReader's extract model, SAX uses a push-in model: the XML processor uses an "Event" to tell the Host application which node data is accessible and which node data is not; the Host Program responds or ignores the requests as needed. In other words, the data is transferred to the host from the SAX processing program. Programmers are bound to argue over the question of who is more advantageous in the pull and push-in processing models, but it is undeniable that both models can work well .. The. NET Framework does not support SAX, but you can use existing SAX tools, such as MSXML analyzer, For Your. NET program.

C # The XMLTextReader class for reading XML documents has some constructor programs to adapt to various situations, such as reading data from an existing data stream or a unified resource location URL. Most commonly, if you want to read XML data from a file, a constructor will serve this purpose. Here is an example (all of my code examples use the C # language. If you prefer the visual basic language, it is easy to convert them ).

 
 
  1. XMLTextReader myReader;  
  2.  
  3. myReader = New XMLTextReader("c:\data\sales.XML")  

Create a loop called the Read () method. The return value of this method is always true until it reaches the bottom of the file. In other words, the loop starts at the beginning of the file and reads all the nodes. One node is read at a time until the end of the file is reached:

 
 
  1. While (myReader. Read ()){
  2. ...
  3. // Process each node here.
  4. ...
  5. }

After each successful Read () call, the XMLTextReader instantiation program contains the information of the current node (that is, the node just Read from the file. We can obtain the above information from the XMLTextReader member, as described in table 1. We can use the NodeType attribute to determine the type of the current node. Based on the node type, the program code can read node data and check whether it has attributes. Whether to ignore it or perform corresponding operations and Processing Based on program needs.

When using the NodeType attribute, it is very important to understand how nodes relate to XML units. For example, you can view the following XML elements:

<City> Chongqing </city>

C # XMLtextReader reading XML documents regard this element as three nodes in the following order:
1. The <city> label is read as the XMLNodeType. Element Node. The Element Name "city" can be obtained from the Name attribute of XMLTextReader.

2. The Text data "Chongqing" is read as a node of the XMLNodeType. Text type. The data "Chongqing" can be obtained from the Value attribute of XMLTextReader.

3. The </city> label is read as a node of the XMLNodeType. EndElement type. Similarly, the element Name "city" can be obtained from the Name attribute of XMLTextReader.

These are three important node types. Other types are described in. NET instructions. For more information, see related documents.

If XMLTextReader encounters an error, such as XML syntax violation, it throws a System. XML. XMLException exception. The code using this class should always be protected (in Try ...... Catch Block), as you will see in the demo program later.

This article is just a fairly simple article about reading the XMLTextReader class of the XML document in C #. The XMLTextReader class has many Members and cannot be described here. XMLTextReader provides considerable flexibility when reading XML data. Even so, I have made a lot of discussions to ensure that readers can compile programs to implement tasks that are often required in the real world, that is, read data from an XML file and output the data in HTML format to display the data in the browser.

This ASP. NET Program (SCRIPT) runs on the server and generates an HTML page to return to the browser. This script is provided in code segment 1, and the XML data file used for work is provided in code segment 2. You can see that the XML file contains a list of links. The purpose of the program is to display the list. To make it easier for us to observe, these lists have been formatted.
Run the program:

1. Save code segment 1 as the XMLTextReader. ASPx file, and code segment 2 as the XMLData. XML file.

2. Place the two files in a virtual folder of the network server that has installed the. NET Framework.

3. Open Internet Explorer and browse this ASPx file. For example, on a LAN server, the URL will be http: // localhost/xmltextreader. ASPx.

Most of the program work is done by the XMLDisplay class, especially by the ProcessXML () method. It reads XML data from a node each time. For the element of interest, the node data is written into the output result together with the node name followed by the colon and the corresponding HTML format tag. At this stage, the "output result" consists of a StringBuilder object in which HTML text is temporarily stored.

The ProcessXML () method is called from the LoadDocument () method. The task executed in this method is to generate an XMLTextReader instantiation program and load the XML file before calling ProcessXML. It also handles exceptions, and then generates error information and displays it in the browser. Finally, this method returns a string that contains either the generated HTML content or the error message if an exception occurs ,.

The program execution starts with the Page_Load () program. This step is automatically executed when the browser requests to browse this page. The code here instantiates the XMLDisplay class and calls its LoadDocument () method. If everything runs normally, formatted HTML-format return values will be copied to a <div> tag on the page. The generated HTML document will be sent back to the browser and displayed.

What about other. NET Framework classes in C # Reading XML documents? For example, how does the XMLDocument class read XML data? Unlike the XMLTextReader class, the XMLDocument class creates a node tree for the entire XML document in the memory. In this way, the XML data can be obtained randomly (in contrast to the linear method in which the XMLTextReader class obtains data), and the XML file data and structure can be modified with perfect flexibility. In addition, XMLDocument allows the execution of XSLT transformations. However, these additional features are at the cost of reduced running speed and more occupation of system resources.

C # Use the XMLTextReader class code segment to read XML documents: XmlTextReader. aspx

 
 
  1. <%@ Import Namespace = "System. Xml" %>
  2. <Script language = "C #" runat = server>
  3. Public class XmlDisplay
  4. File: // This class reads and processes XML files.
  5. {
  6. Public string LoadDocument (String XmlFileName ){
  7. XmlTextReader xmlReader = null;
  8. StringBuilder html = new StringBuilder ();
  9. Try {
  10. File: // create an XMLTextReader instance.
  11. XmlReader = new XmlTextReader (XmlFileName );
  12. // Process XML files
  13. Html. Append (ProcessXml (xmlReader ));
  14. }
  15. Catch (XmlException ex ){
  16. Html. Append ("an XML exception occurred:" +
  17. Ex. ToString ());
  18. }
  19. Catch (Exception ex ){
  20. Html. Append ("a common exception occurred:" +
  21. Ex. ToString ());
  22. }
  23. Finally
  24. {
  25. If (xmlReader! = Null)
  26. XmlReader. Close ();
  27. }
  28. Return html. ToString ();
  29. }
  30. Private string ProcessXml (XmlTextReader xmlReader)
  31. {
  32. StringBuilder temp = new StringBuilder ();
  33. File: // This method reads the XML file and generates the output HTML document.
  34. While (xmlReader. Read ())
  35. {
  36. // Process the start point of an element node.
  37. If (xmlReader. NodeType = XmlNodeType. Element)
  38. {
  39. File: // ignore the <people> and <person> Elements
  40. If (xmlReader. Name! = "Person") & (xmlReader. Name! = "People "))
  41. {
  42. File: // if it is a <category> element, start a new paragraph.
  43. If (xmlReader. Name = "category ")
  44. Temp. Append ("<p> ");
  45. File: // Add the element name to the output
  46. Temp. Append (xmlReader. Name + ":");
  47. }
  48. }
  49. // Process text nodes
  50. Else if (xmlReader. NodeType = XmlNodeType. Text)
  51. Temp. Append (xmlReader. Value + "<br> ");
  52. File: // process the end of an element node
  53. Else if (xmlReader. NodeType = XmlNodeType. EndElement)
  54. {
  55. File: // if it is an <email> node, add the end section mark
  56. If (xmlReader. Name = "email ")
  57. Temp. Append ("</p> ");
  58. }
  59. } // End the while LOOP
  60. Return temp. ToString ();
  61. } File: // end the ProcessXML Method
  62. } File: // end the XmlDisplay class
  63. Private void Page_Load (Object sender, EventArgs e ){
  64. File: // create an XmlDisplay instance
  65. XmlDisplay XmlDisplayDemo = new XmlDisplay ();
  66. Output. InnerHtml = XmlDisplayDemo. LoadDocument (Server. MapPath ("XMLData. xml "));
  67. }
  68. </Script>
  69. <Html>
  70. <Head>
  71. </Head>
  72. <Body>
  73. <H2> Demonstrate XmlTextReader class
  74. <Div id = "output" runat = "server"/>
  75. </Body>
  76. </Html>
  77. Static void Main (string [] args)
  78. {
  79. DateTime d1 = DateTime. Now;
  80. XmlDocumentTest ();
  81. DateTime d2 = DateTime. Now;
  82. Time Span ts = d2-d1;
  83. Console. WriteLine (ts. TotalMilliseconds );
  84. Console. Read ();
  85.  
  86. }
  87.  
  88.  
  89. Public static string XmlFileName = "http://www.cnblogs.com/XML/1.xml ";
  90. Private static void XmlTextReaderTest ()
  91. {
  92. XmlTextReader reader = new XmlTextReader (XmlFileName );
  93. While (reader. Read ())
  94. {
  95. Bool exit = false;
  96. Switch (reader. NodeType)
  97. {
  98. Case XmlNodeType. Element:
  99. Break;
  100. Case XmlNodeType. Text:
  101. If (reader. Value = "last ")
  102. {
  103. Exit = true;
  104. }
  105. Break;
  106. Case XmlNodeType. EndElement:
  107. Break;
  108. Default:
  109. Break;
  110. }
  111. If (exit)
  112. {
  113. Return;
  114. }
  115.  
  116. }
  117. }
  118.  
  119. Private static void XmlDocumentTest ()
  120. {
  121. XmlDocument xd = new XmlDocument ();
  122. Xd. Load (XmlFileName );
  123. XmlNode node = xd. SelectSingleNode ("/people/person [category = 'last']");
  124. Console. Write (node. Name );
  125. }

C # The method for reading XML documents using the XMLTextReader class is introduced here. I hope it will help you understand and learn C # Reading XML documents using the XMLTextReader class.

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.