I saw an article on the Internet and tried it myself. Sure enough, XMLTextReader is faster!
The XMLTextReader class included in the System.XML namespace of the .NET Framework can quickly read data from XML files without being very demanding on system resources. Use the XMLTextReader class to read data from XML files and convert it into HTML format for output in the browser.
Before reading this article, readers need to understand some basic knowledge: XML, HTML, C# programming language, and some knowledge of .NET, especially the ASP.NET framework.
Microsoft's .NET framework provides developers with many development conveniences. As the importance of XML continues to grow, developers are looking forward to the development of a complete set of powerful XML tools. The .NET framework has lived up to our expectations and organized the following classes for XML in the System.XML namespace:
XMLTextReader------Provides fast, one-way, unbuffered access. XML data. (One-way means you can only read the XML file from front to back, not reverse)
XMLValidatingReader------Used with the XMLTextReader class, it provides the ability to verify DTD, XDR and XSD schemas.
XMLDocument------follows the primary and secondary standards of the W3C Document Object Model specification to achieve random and cached access to XML data. The first level contains the most basic parts of the DOM, while the second level adds a variety of improvements, including adding support for namespaces and cascading charts (CSS).
XMLTextWriter------Generate XML files that comply with the W3C XML 1.0 specification.
This article mainly talks about the first class XMLTextReader. The purpose of this class is to quickly read data from XML files without placing high demands on system resources (mainly including memory and processor time). Under the control of the parent program, it implements this working process by gradually operating the XML file by processing only one node at a time. In each node of the XML file, the parent program can determine the type of the node, its attributes and data (if any), and other information about the node. Based on this information, the parent program can choose whether to process this node or ignore the node's information to meet the needs of various application requests. This is called the pull processing model because the parent program makes the request and extracts the individual nodes from the XML file and then processes it or not processes it as needed.
We can compare the XMLTextReader class with the XML Simple Application Programming Interface, or SAX, which is another technology for reading XML data that is very popular among programmers. XMLTextReader and SAX are very similar in that they can quickly read data from XML files without taking up a lot of system resources. However, unlike the extraction model of XMLTextReader, SAX uses a push model: the XML processor uses "events" to inform the host application which node data is available and which cannot be obtained; as needed, the host program responds accordingly react or ignore it. In other words, the data is pushed from the SAX handler to the host. Programmers are bound to debate whether the pull-out or push-in processing models have more advantages, but there is no denying that both models work well. The .NET Framework does not support SAX, but you can use existing SAX tools, such as the MSXML parser, with your .NET applications.
The XMLTextReader class has constructors to accommodate a variety of situations, such as reading data from an existing data stream or Uniform Resource Locator. Most commonly, you may want to read XML data from a file, and there is a corresponding constructor to serve this. Here's an example (all my code examples are in C#, they're easy to convert if you prefer to use VISUAL BASIC).
XMLTextReader myReader;
myReader = New XMLTextReader("c:datasales.XML")
creates a loop called the Read() method. The return value of this method is always true until it reaches the bottom of the file, when the return value becomes false. . In other words, the loop starts at the beginning of the file and reads in all nodes, one at a time, until the end of the file is reached:
While (myReader.Read()) {
...
// Process each node here.
...
}
After each successful call to Read(), the XMLTextReader instantiation program contains information about the current node (that is, the node just read from the file). We can obtain the above information from the members of XMLTextReader, just as described in Table 1; and determine the type of the current node through the NodeType attribute. Based on the node type, the program code can read the node data, check whether it has attributes, and whether to ignore it or perform corresponding operations and processing according to the needs of the program.
When using the NodeType attribute, it is important to understand how nodes are related to XML cells. For example, look at the following XML element:
<city>Chongqing</city>
XMLtextReader regards this element as 3 nodes, in the following order:
1. The <city> tag is read as a node of type XMLNodeType.Element, and the name of the element "city" can be obtained from the Name attribute of XMLTextReader.
2. The text data "Chongqing" is read as a node of type XMLNodeType.Text. The data "Chongqing" can be obtained from the Value attribute of XMLTextReader.
3. The </city> tag is read as a node of type XMLNodeType.EndElement. Likewise, the name of the element "city" is available from the XMLTextReader's Name property.
These are three important node types. Other types are described in detail in the .NET documentation. Please refer to the relevant information.
If XMLTextReader encounters an error, such as a violation of XML syntax, it throws an exception of type System.XML.XMLException. Code using this class should always be protected (in a Try...Catch block), as you will see later in the demo program.
This article is just a fairly simple introduction to the XMLTextReader class. The XMLTextReader class has quite a few members, and it is impossible to mention them all here. XMLTextReader provides considerable flexibility when reading XML data. Even so, I still discussed a lot to ensure that readers can write programs to achieve tasks that are often required in the real world, which is to read data from an XML file and then output it in HTML format to implement it in the browser. display.
This ASP.NET program (script) runs on the server and generates an HTML page back to the browser. The script is given in Snippet 1, and the XML data file it works with is given in Snippet 2. You can see that this XML file contains a list of relationships; the goal of the program is to display this list, which has been formatted to make it easier for us to see.
Run the program:
1. Save code snippet 1 as an XMLTextReader.ASPx file and code snippet 2 as an XMLData.XML file.
2. Place both files in a virtual folder on a web server that has the .NET Framework installed.
3. Open Internet Explorer and browse to the ASPx file, for example, on a LAN server, the URL would be http://localhost/xmltextreader.ASPx ;.
Most of the program's work is done by the XMLDisplay class, specifically by the ProcessXML() method. It reads one node XML data at a time. For the element of interest, the node data and the node name followed by a colon will be written to the output result together with the corresponding HTML formatting tag. At this stage, the "output result" consists of a StringBuilder object in which the HTML text is temporarily stored.
The ProcessXML() method is called from the LoadDocument() method. The task performed by this method is to generate an XMLTextReader instantiation program and load the XML file before calling ProcessXML. It also handles exceptions and subsequently generates error messages and displays them in the browser. Ultimately the method returns a string containing either the generated HTML content or an error message if an exception occurred.
Program execution starts with the Page_Load() program. When the browser requests to browse this page, this step will be executed automatically. The code here instantiates the XMLDisplay class and calls its LoadDocument() method. If everything runs normally, the formatted HTML return value will be copied to a <div> tag on the page, and the generated HTML document will be sent back to the browser and displayed.
How do other .NET Framework classes, such as the XMLDocument class, perform in reading XML data? The XMLDocument class differs from the XMLTextReader class in that it creates a node tree of the entire XML document in memory. In this way, XML data can be obtained randomly (just the opposite of the linear way in which the XMLTextReader class obtains data), and it has perfect flexibility when modifying the data and structure of the XML file. In addition, XMLDocument allows you to perform XSLT transformations, but these additional features come at the expense of slower running speed and greater usage of system resources.
Code snippet 1: XmlTextReader.aspx
<%@ Import Namespace="System.Xml" %>
<script language="C#" runat=server>
public class XmlDisplay
file://This class reads and processes XML files.
{
public string LoadDocument(String XmlFileName) {
XmlTextReader xmlReader = null;
StringBuilder html = new StringBuilder();
try {
file:// creates an instance of XMLTextReader.
xmlReader = new XmlTextReader(XmlFileName);
// Process XML files
html.Append(ProcessXml(xmlReader));
}
catch (XmlException ex){
html.Append("An XML exception occurred: " +
ex.ToString());
}
catch (Exception ex){
html.Append("A common exception occurred: " +
ex.ToString());
}
finally
{
if (xmlReader != null)
xmlReader.Close();
}
return html.ToString();
}
private string ProcessXml(XmlTextReader xmlReader)
{
StringBuilder temp = new StringBuilder();
file://This method reads the XML file and generates the output HTML document.
while (xmlReader.Read())
{
// Handle the start of an element node.
if (xmlReader.NodeType == XmlNodeType.Element)
{
file://ignores <people> and <person> elements
if ((xmlReader.Name != "person") && (xmlReader.Name != "people"))
{
file://If it is a <category> element, start a new paragraph
if (xmlReader.Name == "category" )
temp.Append("<p>");
file://adds element names to the output
temp.Append( xmlReader.Name + ": " );
}
}
// Process text nodes
else if (xmlReader.NodeType == XmlNodeType.Text)
temp.Append(xmlReader.Value + "<br>");
file:// handles the end of element node
else if (xmlReader.NodeType == XmlNodeType.EndElement)
{
If file:// is an <email> node, add a tag to end the paragraph.
if (xmlReader.Name == "email" )
temp.Append("</p>");
}
}//End the while loop
return temp.ToString();
} file://End ProcessXML method
} file://End XmlDisplay class
private void Page_Load(Object sender, EventArgs e){
file://Create an instance of the XmlDisplay class
XmlDisplay XmlDisplayDemo = new XmlDisplay();
output.InnerHtml = XmlDisplayDemo.LoadDocument(Server.MapPath("XMLData.xml"));
}
</script>
<html>
<head>
</head>
<body>
<h2>Demo XmlTextReader class</h2>
<div id="output" runat="server"/>
</body>
</html>
1 static void Main(string[] args)
2 {
3 DateTime d1 =DateTime.Now;
4 XmlDocumentTest();
5 DateTime d2 =DateTime.Now;
6 TimeSpan ts =d2-d1;
7
8 Console.WriteLine(ts.TotalMilliseconds);
9 Console.Read();
10
11 }
12
13
14 public static string XmlFileName = "../../XML/1.xml";
15
16 private static void XmlTextReaderTest()
17 {
18 XmlTextReader reader = new XmlTextReader(XmlFileName);
19 while (reader.Read() )
20 {
21 bool exit =false;
22 switch(reader.NodeType)
twenty three {
24 case XmlNodeType.Element:
25 break;
26 case XmlNodeType.Text:
27 if (reader.Value=="last")
28 {
29 exit=true;
30}
31 break;
32 case XmlNodeType.EndElement:
33 break;
34 default:
35 break;
36}
37 if(exit)
38 {
39 return;
40
41 }
42
43}
44}
45
46 private static void XmlDocumentTest()
47 {
48 XmlDocument xd =new XmlDocument();
49 xd.Load(XmlFileName);
50 XmlNode node = xd.SelectSingleNode("/people/person[category='last']");
51 Console.Write(node.Name);
52 }
It turns out that the first one takes a long time:
It turns out that the second one is time-consuming:
http://www.cnblogs.com/goody9807/archive/2006/10/24/534888.html