How to read XML files using XmlReader in C # _c# tutorial

Source: Internet
Author: User
Tags cdata

XmlReader provides us with a minimal resource-consuming way to parse XML data by reading the document forward and identifying the read elements. Most of the time we use XmlReader to validate the data validation of an XML file (using the Read () method of the XmlReader instance to read all the nodes sequentially to determine whether it matches the specified pattern). With this kind of non caching, read-only, forward-only way, a small amount of data is put into memory each time, and the memory footprint is small, which is the best choice for reading large XML files.

Let's take a look at the steps of the XmlReader class reading an XML file:

1, create an instance of the class using the Create () factory method of the XmlReader class, and pass the read XML filename as a parameter to the method;

2. Create a loop that calls the read () method repeatedly. This method starts at the first node of the file and reads all remaining nodes, but only one node is read per call. Returns true if one node can be read, and returns False when the end of the file is reached;

3. In this loop, the properties and methods of the XmlReader instance are checked to obtain information about the current node (type, name, data, and so on). Keep looping until read () returns false;

Let's look at an example:

Employees.xml file:

<?xml version= ' 1.0 '?>
<employees>
 <employee id= "1" > 
 <name>
 <firstname >Nancy</firstName>
 <lastName>Davolio</lastName> 
 </name>
 <city> seattle</city>
 <state>WA</state>
 <zipCode>98122</zipCode> 
 </ employee>
 <employee id= "2" > 
 <name>
 <firstName>Andrew</firstName>
 <lastName>Fuller</lastName>
 </name>
 <city>Tacoma</city>
 <state>WA</state>
 <zipCode>98401</zipCode> 
 </employee> 
</ Employees>

ASPX code:

<%@ Page language= "C #"%> <%@ Import namespace= ' system.xml '%> <script ' runat= ' server ' > void Page_Load (
 Object sender, EventArgs e) {//location of XML file string xmlfilepath = Server.MapPath ("~/employees.xml");
 try {using (XmlReader reader = Xmlreader.create (Xmlfilepath)) {string result; while (reader. Read ()) {//process Only the elements if reader.
 NodeType = = xmlnodetype.element) {result = ""; for (int count = 1; Count <= reader. Depth;
 count++) {result = = "= ="; result = = "=>" + reader.
 Name + "<br/>";
 Lblresult.text + = result; catch (Exception ex) {lblresult.text = "An Exception occurred:" + ex.
 message; } </script>  

Output results:

=> Employees
====> Employee
=======> Name
==========> FirstName
==========> LastName
=======> City
=======> State
=======> ZipCode
====> Employee
=======> Name
==========> FirstName
==========> LastName
=======> City
=======> State
=======> ZipCode

Let's look at the properties and methods of the XmlReader class:

Property Description
Attributecount Returns the number of properties for the current node
Depth Returns the depth of the current node to determine whether the specified node has child nodes
Eof To determine whether the reader is at the end of the stream
Hasattribute Returns a Boolean value indicating whether the current node has an attribute
HasValue Returns a Boolean value indicating whether the current node has a value
Isemptyelement Determines whether the current node is an empty element
LocalName Returns the local name of the current node
Name Returns the qualified name of the current node
NamespaceURI Returns the namespace URI of the current node
NodeType Returns the node type of the current node as a XmlNodeType enumeration
Prefix Returns the namespace prefix associated with the current node
ReadState Returns the current state of the reader in the form of a ReadState enumeration
Settings Returns the XmlReaderSettings object used to create the XmlReader instance
Value Returns the value of the current node
ValueType Get the CLR type of the current node

Important ways to XmlReader classes:

Method Description
Close Close the XmlReader object by setting the ReadState enumeration to Closed
Create Creates an instance of the XmlReader object and returns it to the calling program
GetAttribute Get the value of a property
Isstartelement Indicates whether the current node is a start tag
MoveToAttribute Move the reader to the specified property
MoveToContent If the current node is not a content node, move the reader to the next content node
Movetoelement Moves the reader to the element that contains the current property; To enumerate properties and to switch to elements that contain all of these properties
MoveToFirstAttribute Move the reader to the first property of the current node
MoveToNextAttribute Move the reader to the next property of the current node
Read Reading the next node from the stream
ReadContentAs Reading the contents of an object that provides a type
ReadElementContentAs Reads the current element and returns the contents of the specified type object
Readendelement Move reader over current end tag and move to next node
ReadInnerXml Reads all contents of the current node, including markup, as a string
Readoutxml Read the contents of a node, including the current node tag and child nodes
Readtodescendant Move the reader to the next node that matches the descendant element
Readtofollowing Keep reading until you find the specified element
Readtonextslibing Move the reader to the next node that matches the sibling element
Readvaluechunk Allows reading of large text streams embedded in XML documents

XmlNodeType members of the enumeration:

Members Description
Attribute Property
Cdata CDATA Region
Comment XML annotations
Document Document object that represents the root of the XML tree
DocumentFragment Document fragment
DocumentType Document Type declaration
Element,endelement Start element and end element
Entity,endentity Start entity declaration and end Entity declaration
EntityReference Entity references (such as <)
None There is no read node and query node type use
notation Symbol entries in the DTD
ProcessingInstruction XML processing Instructions
SignificantWhitespace White space in a mixed content model document, or when Xml:space=preserve is set up using the
Text The textual content of the element
Whitespace whitespace between tags
XmlDeclaration XML declaration at the top of the document

Important attributes of the XmlReaderSettings class:

Property Description
Checkcharacters Allows you to get or set a value that indicates whether the character check is performed
ConformanceLevel To obtain or set the XmlReader object's compliance requirements
Ignorecomment Allows you to get or set a value that indicates whether the annotation is ignored
IgnoreprocessinginstructIon Specifies whether to ignore processing instructions
Ignorewhitespace Specify whether to ignore meaningless spaces
ProhibitDTD Specifies whether DTD processing is allowed
Schemas Specifies the XmlSchemaSet to use when performing XML validation
Validationflags Gets or sets the value used to specify the mode validation settings
ValidationType Gets or sets a value that specifies the type of validation to be performed
XmlResolver Set up a xmlreslover for accessing external documents

With the XmlReaderSettings class, you can specify a series of features supported by the XmlReader object, so simply pass xmlreadersettings as a parameter into the XmlReader create () method. As shown below:

 <script runat= "server" > void Page_Load (object sender, EventArgs e) {string x 
 Mlfilepath = Server.MapPath ("~/employees.xml"); Create the XmlReaderSettings object and set appropriate properties xmlreadersettings settings = new XmlReaderSettings ()
 ; Settings.
 Ignorecomments = true; Settings.
 Ignorewhitespace = true; try {//get reference to the XmlReader object using (XmlReader reader = xmlreader.create (Xmlfilepath, Settings)) {St
 Ring result; while (reader. Read ()) {//process Only the elements if reader.
 NodeType = = xmlnodetype.element) {//reset The variable for a new Element result = ""; for (int count = 1; Count <= reader. Depth;
 count++) {result = = "= ="; result = = "=>" + reader.
 Name + "<br/>";
 Lblresult.text + = result; catch (Exception ex) {lblresult.text = "An Exception occurred:" + ex.
 message; } </script> 

In summary, we can use the XmlReader class to read XML files in a non cached, read-only, forward-only way, which takes up less memory and is recommended for everyone to use.

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.