Xml
XmlTextReader classes contained in the System.Xml namespace of the. NET Framework do not require high system resources to quickly read data from an XML file. You can use the XmlTextReader class to read data from an XML file and convert it to HTML format to output in a browser.
Before reading this article, readers need to know some basic knowledge: XML, HTML, C # programming language, and. NET in particular the ASP.net framework of some knowledge.
Microsoft Inc. 's. NET Framework gives developers a lot of development convenience, and as XML grows in importance, developers are looking forward to a powerful set of XML tools being developed. NET Framework has not lived up to our expectations, the following several classes are organized into XML in the System.Xml namespace:
XmlTextReader------provides fast, one-way, and buffer-free access to XML data. (one-way means you can only read XML files from the trip, not backwards)
XmlValidatingReader------is used with the XmlTextReader class to provide the ability to validate DTD, XDR, and XSD schemas.
XmlDocument------Follow the first and two levels of standard for the Document Object model of the consortium to implement random, cached access to XML data. Level level contains the most basic part of the DOM, while the secondary level adds a variety of improvements, including increased support for namespaces and cascading charts (CSS).
XmlTextWriter------Generate XML files that follow the XML 1.0 specification of the Consortium.
This article focuses on the first class XmlTextReader, which is designed to quickly read data from an XML file, but does not require high requirements for system resources (mainly memory and processor time). Under the control of the parent program, it implements this process by progressively manipulating the XML file each time it processes only one node. In each node of the XML file, the parent program determines the type of the node, its properties 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's information to meet the needs of various application requests. This is called the extraction (pull) processing model, because the parent program makes the request and extracts the nodes from the XML file and then processes it as needed or does not process it.
We can compare the XmlTextReader class with the XML simple application interface, sax, which is another technique that is very popular among programmers in reading XML data. XmlTextReader and sax are similar in that they do not need to consume a lot of system resources to quickly read data from XML files. However, unlike the XmlTextReader extract model, Sax uses a push model: An XML processor informs the host application which node data is available, which is not available, and, as needed, the host program responds to or ignores it. In other words, the transfer direction of data is pushed from the sax handler to the host. Programmers are bound to argue over the question of who has the advantage of the decimation and push-style processing model, 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 analyzer, for your. NET program.
The XmlTextReader class has some constructors to accommodate a variety of situations, such as reading data from an existing data stream or a unified resource Locator URL. Most commonly, you may want to read XML data from a file, and then there is a corresponding constructor to serve it. Here's an example (all my code examples use the C # language, and if you prefer to use the Visual Basic language, they're easy to convert).
XmlTextReader myreader;
myreader = New XmlTextReader ("C:\Data\Sales. XML ")
Creates a loop called the Read () method, which is always true until the return value becomes false until the bottom of the file is reached. In other words, the loop starts at the beginning of the file and reads all the nodes, reading a node at a time until the end of the file is reached:
while (Myreader.read ()) {
...
Handle each node here.
...
}
After each successful call to read (), the XmlTextReader instantiation contains information about the current node (that is, the node that was just read from the file). This information can be obtained from members of the XmlTextReader, as described in Table 1, and the type of the current node is determined by the NodeType property. On the basis of the node type, the code of the program can read the node data, check whether it has attributes, ignore it or do the corresponding operation and processing according to the program.
When using the NodeType attribute, it is important to understand how the node is connected to the XML unit. For example, look at the following XML elements:
Chongqing
XmlTextReader this element as 3 nodes, in the following order:
1. The label is read as a type XmlNodeType.Element node, and the name "city" of the element can be obtained from the XmlTextReader name property.
2. The text data "Chongqing" is read as a node of type XmlNodeType.Text. The data "Chongqing" can be obtained from the XmlTextReader value property.
3. The label is read as a type xmlnodetype.endelement node. Similarly, the name "city" of an element can be obtained from the XmlTextReader name property.
This is 3 important node types, and the other types are in. NET's documentation, please refer to the relevant information.
If XmlTextReader encounters an error, such as a violation of the XML syntax, it throws a System.XML.XMLException type of exception. Code that uses this class should always be protected (in a try ...). Catch block), as you will see in the demo program later.
This article is just a fairly simple introduction to the XmlTextReader class of articles, XmlTextReader class has a considerable number of members, here can not be described in one by one. XmlTextReader can provide considerable flexibility when reading XML data. Even so, I still have a lot of discussion to ensure that readers can compile programs to achieve the tasks that are often required in the real world, that is, to read data from an XML file and then output it in HTML format, thus realizing the display 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 given in code Snippet 1, and the XML data file it uses to work on is given in code segment 2. You can see that the XML file contains a list of relationships, and the goal of the program is to show the list, and to make it easier for us to observe, the lists have been formatted.
To run the program:
1. Save the Code Snippet 1 as a xmltextreader.aspx file and save the code Snippet 2 as a xmldata.xml file.
2. Put all two files in a virtual folder on a network server that already has the. NET Framework installed.
3. Open Internet Explorer and browse this ASPX file, for example, on a LAN server, the URL will be localhost/xmltextreader. ASPx.
Most of the program work is done by the Xmldisplay class, especially by the Processxml () method. It reads one node of XML data at a time, and the node data and the node name followed by the colon and the corresponding HTML formatting label are written to the output results for the element of interest. At this stage, the "output result" consists of a StringBuilder object that is temporarily stored in an HTML text.
The Processxml () method is called from the Loaddocument () method. This method performs the task of generating an XmlTextReader instantiation and loading the XML file before calling Processxml. It also handles exceptions and then generates the wrong information and displays them in the browser. Eventually the method returns a string that contains either the resulting HTML content or, if the exception occurs, an error message.
Program execution starts with the Page_Load () program, which is automatically performed when the browser requests to browse the page. The code here instantiates the Xmldisplay class and invokes its Loaddocument () method. If everything works, the formatted HTML return value is copied to a
tab in the page, and the resulting HTML document is sent back to the browser and displayed.
What about the other. NET framework classes, such as the XmlDocument class, in reading XML data? Unlike the XmlTextReader class, the XmlDocument class creates a node tree of the entire XML document in memory. This allows the random acquisition of XML data (in contrast to the linear way in which the XmlTextReader class obtains data) and has the perfect flexibility to modify the data and structure of the XML file. In addition, XmlDocument allows XSLT transformations to be performed, but these additional features are at the expense of slower operating speeds and more system resource consumption.
Code Snippet 1:xmltextreader.aspx
<%@ Import namespace= "System.Xml"%>
public class Xmldisplay
FILE://this class to read into and process the XML file.
{
public string Loaddocument (string xmlfilename) {
XmlTextReader xmlReader = null;
StringBuilder html = new StringBuilder ();
try {
FILE://creates an instance of XmlTextReader.
XmlReader = new XmlTextReader (XMLfileName);
Working with XML files
Html. Append (Processxml (XmlReader));
}
catch (XmlException ex) {
Html. Append ("An XML exception occurred:" +
Ex. ToString ());
}
catch (Exception ex) {
Html. Append ("A normal exception occurs:" +
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 ())
{
Handles the start of an element node.
if (Xmlreader.nodetype = = XmlNodeType.Element)
{
file://Ignore and elements
if ((xmlreader.name!= "person") && (xmlreader.name!= "People"))
{
file://if it's a element, start a new paragraph
if (Xmlreader.name = = "category")
Temp. Append ("
");
file://add element name to output
Temp. Append (Xmlreader.name + ":");
}
}
Working with text nodes
else if (Xmlreader.nodetype = = XmlNodeType.Text)
Temp. Append (Xmlreader.value + "
");
file://processing the end of an element node
else if (Xmlreader.nodetype = = xmlnodetype.endelement)
{
file://if it is a node, add the tag for the end paragraph
if (xmlreader.name = = "email")
Temp. Append ("
");
}
}//End 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"));
}
Demo XmlTextReader class
Code Snippet 2:xmldata.xml
Friends
Ark
111-222-333
tjfangzhou@yesky.com
Family
mom
555-666-7777
mother@family.com
Family
dad
123-456-7890
father@family.com
Friends
Quiet
999-999-9999
jingjing@girlfriend.com