System.Xml.XmlTextReader Class

Assembly: System.Xml.dll
Namespace: System.Xml
Summary
Represents a reader that provides fast, non-cached, forward-only access to XML data.
C# Syntax:
public class XmlTextReader : XmlReader, IXmlLineInfo
Remarks
XmlTextReader provides forward-only, read-only access to a stream of XML data. The current node refers to the node on which the reader is positioned. The reader is advanced using any of the read methods and properties reflect the value of the current node.

This class implements XmlReader and conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations.XmlTextReader provides the following functionality:

Because the XmlTextReader does not perform the extra checks required for data validation, it provides a fast well-formedness parser.

To perform data validation, use XmlValidatingReader.

To read XML data from an XmlDocument, use XmlNodeReader.

To read strongly typed data, use the XmlConvert class. For example, the following C# code reads in data and converts it from a String to a Double.

          Double price = XmlConvert.ToDouble(reader.Value);
        

XmlTextReader throws an XmlException on XML parse errors. After an exception is thrown the state of the reader is not predictable. For example, the reported node type may be different than the actual node type of the current node.

For further discussion on the XmlReader classes, see the conceptual topic at MSDN: readingxmlwithxmlreader.

See also:
System.Xml Namespace

System.Xml.XmlTextReader Member List:

Public Constructors
ctor #2 Overloaded:
.ctor(Stream input)

Initializes a new instance of the XmlTextReader class with the specified stream.
ctor #3 Overloaded:
.ctor(string url)

Initializes a new instance of the XmlTextReader class with the specified file.
ctor #4 Overloaded:
.ctor(TextReader input)

Initializes a new instance of the XmlTextReader class with the specified TextReader.
ctor #6 Overloaded:
.ctor(Stream input, XmlNameTable nt)

Initializes a new instance of the XmlTextReader class with the specified stream and XmlNameTable.
ctor #7 Overloaded:
.ctor(string url, Stream input)

Initializes a new instance of the XmlTextReader class with the specified URL and stream.
ctor #8 Overloaded:
.ctor(string url, TextReader input)

Initializes a new instance of the XmlTextReader class with the specified URL and TextReader.
ctor #9 Overloaded:
.ctor(string url, XmlNameTable nt)

Initializes a new instance of the XmlTextReader class with the specified file and XmlNameTable.
ctor #10 Overloaded:
.ctor(TextReader input, XmlNameTable nt)

Initializes a new instance of the XmlTextReader class with the specified TextReader and XmlNameTable.
ctor #11 Overloaded:
.ctor(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context)

Initializes a new instance of the XmlTextReader class with the specified values.
ctor #12 Overloaded:
.ctor(string url, Stream input, XmlNameTable nt)

Initializes a new instance of the XmlTextReader class with the specified URL, stream and XmlNameTable.
ctor #13 Overloaded:
.ctor(string url, TextReader input, XmlNameTable nt)

Initializes a new instance of the XmlTextReader class with the specified URL, TextReader and XmlNameTable.
ctor #14 Overloaded:
.ctor(string xmlFragment, XmlNodeType fragType, XmlParserContext context)

Initializes a new instance of the XmlTextReader class with the specified values.
Public Properties
AttributeCount Read-only

Overridden:
Gets the number of attributes on the current node.
BaseURI Read-only

Overridden:
Gets the base URI of the current node.
CanResolveEntity
(inherited from System.Xml.XmlReader)
Read-only

See base class member description: System.Xml.XmlReader.CanResolveEntity


Gets a value indicating whether this reader can parse and resolve entities.
Depth Read-only

Overridden:
Gets the depth of the current node in the XML document.
Encoding Read-only

Gets the encoding of the document.
EOF Read-only

Overridden:
Gets a value indicating whether the reader is positioned at the end of the stream.
HasAttributes
(inherited from System.Xml.XmlReader)
Read-only

See base class member description: System.Xml.XmlReader.HasAttributes


Gets a value indicating whether the current node has any attributes.
HasValue Read-only

Overridden:
Gets a value indicating whether the current node can have a XmlTextReader.Value.
IsDefault Read-only

Overridden:
Gets a value indicating whether the current node is an attribute that was generated from the default value defined in the DTD or schema.
IsEmptyElement Read-only

Overridden:
Gets a value indicating whether the current node is an empty element (for example, <MyElement/> ).
Item Read-only

Overloaded:
Item[int i] {get

Overridden:
Gets the value of the attribute with the specified index.
Item Read-only

Overloaded:
Item[string name] {get

Overridden:
Gets the value of the attribute with the specified name.
Item Read-only

Overloaded:
Item[string name, string namespaceURI] {get

Overridden:
Gets the value of the attribute with the specified local name and namespace URI.
LineNumber Read-only

Gets the current line number.
LinePosition Read-only

Gets the current line position.
LocalName Read-only

Overridden:
Gets the local name of the current node.
Name Read-only

Overridden:
Gets the qualified name of the current node.
Namespaces Read-write

Gets or sets a value indicating whether to do namespace support.
NamespaceURI Read-only

Overridden:
Gets the namespace URI (as defined in the W3C Namespace specification) of the node on which the reader is positioned.
NameTable Read-only

Overridden:
Gets the XmlNameTable associated with this implementation.
NodeType Read-only

Overridden:
Gets the type of the current node.
Normalization Read-write

Gets or sets a value indicating whether to normalize white space and attribute values.
Prefix Read-only

Overridden:
Gets the namespace prefix associated with the current node.
QuoteChar Read-only

Overridden:
Gets the quotation mark character used to enclose the value of an attribute node.
ReadState Read-only

Overridden:
Gets the state of the reader.
Value Read-only

Overridden:
Gets the text value of the current node.
WhitespaceHandling Read-write

Gets or sets a value that specifies how white space is handled.
XmlLang Read-only

Overridden:
Gets the current xml:lang scope.
XmlResolver Write-only

Sets the XmlResolver used for resolving DTD references.
XmlSpace Read-only

Overridden:
Gets the current xml:space scope.
Public Methods
Close Overridden:
Changes the XmlReader.ReadState to Closed.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
GetAttribute Overloaded:
GetAttribute(int i)

Overridden:
Gets the value of the attribute with the specified index.
GetAttribute Overloaded:
GetAttribute(string name)

Overridden:
Gets the value of the attribute with the specified name.
GetAttribute Overloaded:
GetAttribute(string localName, string namespaceURI)

Overridden:
Gets the value of the attribute with the specified local name and namespace URI.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetRemainder Gets the remainder of the buffered XML.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
IsStartElement
(inherited from System.Xml.XmlReader)
Overloaded:
IsStartElement()

See base class member description: System.Xml.XmlReader.IsStartElement


Calls XmlReader.MoveToContent and tests if the current content node is a start tag or empty element tag.
IsStartElement
(inherited from System.Xml.XmlReader)
Overloaded:
IsStartElement(string name)

See base class member description: System.Xml.XmlReader.IsStartElement


Calls XmlReader.MoveToContent and tests if the current content node is a start tag or empty element tag and if the XmlReader.Name property of the element found matches the given argument.
IsStartElement
(inherited from System.Xml.XmlReader)
Overloaded:
IsStartElement(string localname, string ns)

See base class member description: System.Xml.XmlReader.IsStartElement


Calls XmlReader.MoveToContent and tests if the current content node is a start tag or empty element tag and if the XmlReader.LocalName and XmlReader.NamespaceURI properties of the element found match the given strings.
LookupNamespace Overridden:
Resolves a namespace prefix in the current element's scope.
MoveToAttribute Overloaded:
MoveToAttribute(int i)

Overridden:
Moves to the attribute with the specified index.
MoveToAttribute Overloaded:
MoveToAttribute(string name)

Overridden:
Moves to the attribute with the specified name.
MoveToAttribute Overloaded:
MoveToAttribute(string localName, string namespaceURI)

Overridden:
Moves to the attribute with the specified local name and namespace URI.
MoveToContent
(inherited from System.Xml.XmlReader)
See base class member description: System.Xml.XmlReader.MoveToContent


Checks whether the current node is a content (non-white space text, CDATA, Element, EndElement, EntityReference, or EndEntity) node. If the node is not a content node, the reader skips ahead to the next content node or end of file. It skips over nodes of the following type: ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace.
MoveToElement Overridden:
Moves to the element that contains the current attribute node.
MoveToFirstAttribute Overridden:
Moves to the first attribute.
MoveToNextAttribute Overridden:
Moves to the next attribute.
Read Overridden:
Reads the next node from the stream.
ReadAttributeValue Overridden:
Parses the attribute value into one or more Text, EntityReference, or EndEntity nodes.
ReadBase64 Decodes Base64 and returns the decoded binary bytes.
ReadBinHex Decodes BinHex and returns the decoded binary bytes.
ReadChars Reads the text contents of an element into a character buffer. This method is designed to read large streams of embedded text by calling it successively.
ReadElementString
(inherited from System.Xml.XmlReader)
Overloaded:
ReadElementString()

See base class member description: System.Xml.XmlReader.ReadElementString


Reads a text-only element.
ReadElementString
(inherited from System.Xml.XmlReader)
Overloaded:
ReadElementString(string name)

See base class member description: System.Xml.XmlReader.ReadElementString


Checks that the XmlReader.Name property of the element found matches the given string before reading a text-only element.
ReadElementString
(inherited from System.Xml.XmlReader)
Overloaded:
ReadElementString(string localname, string ns)

See base class member description: System.Xml.XmlReader.ReadElementString


Checks that the XmlReader.LocalName and XmlReader.NamespaceURI properties of the element found matches the given strings before reading a text-only element.
ReadEndElement
(inherited from System.Xml.XmlReader)
See base class member description: System.Xml.XmlReader.ReadEndElement


Checks that the current content node is an end tag and advances the reader to the next node.
ReadInnerXml Overridden:
Reads all the content, including markup, as a string.
ReadOuterXml Overridden:
Reads the content, including markup, representing this node and all its children.
ReadStartElement
(inherited from System.Xml.XmlReader)
Overloaded:
ReadStartElement()

See base class member description: System.Xml.XmlReader.ReadStartElement


Checks that the current node is an element and advances the reader to the next node.
ReadStartElement
(inherited from System.Xml.XmlReader)
Overloaded:
ReadStartElement(string name)

See base class member description: System.Xml.XmlReader.ReadStartElement


Checks that the current content node is an element with the given XmlReader.Name and advances the reader to the next node.
ReadStartElement
(inherited from System.Xml.XmlReader)
Overloaded:
ReadStartElement(string localname, string ns)

See base class member description: System.Xml.XmlReader.ReadStartElement


Checks that the current content node is an element with the given XmlReader.LocalName and XmlReader.NamespaceURI and advances the reader to the next node.
ReadString Overridden:
Reads the contents of an element or a text node as a string.
ResetState Resets the state of the reader to ReadState.Initial.
ResolveEntity Overridden:
Resolves the entity reference for EntityReference nodes.
Skip
(inherited from System.Xml.XmlReader)
See base class member description: System.Xml.XmlReader.Skip


Skips the children of the current node.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
Protected Constructors
ctor #1 Overloaded:
.ctor()

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
Initializes a new instance of the XmlTextReader.
ctor #5 Overloaded:
.ctor(XmlNameTable nt)

Initializes a new instance of the XmlTextReader class with the specified XmlNameTable.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Xml.XmlTextReader Member Details

Overloaded ctor #1
Summary
Initializes a new instance of the XmlTextReader.

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
protected XmlTextReader();

Return to top


Overloaded ctor #2
Summary
Initializes a new instance of the XmlTextReader class with the specified stream.
C# Syntax:
public XmlTextReader(
   Stream input
);
Parameters:

input

The stream containing the XML data to read.

Remarks
The XmlTextReader decodes the stream using Encoding.

Return to top


Overloaded ctor #3
Summary
Initializes a new instance of the XmlTextReader class with the specified file.
C# Syntax:
public XmlTextReader(
   string url
);
Parameters:

url

The URL for the file containing the XML data.

Example
The following example reads an XML file and displays each of the nodes.


using System;
using System.IO;
using System.Xml;

//Reads an XML document

public class Sample
{
  private const String filename = "items.xml";

  public static void Main()
  {
     XmlTextReader reader = null;

     try
     {  
        //Load the reader with the data file and ignore all white space nodes.         
        reader = new XmlTextReader(filename);
        reader.WhitespaceHandling = WhitespaceHandling.None;

        //Parse the file and display each of the nodes.
        while (reader.Read())
        {
           switch (reader.NodeType)
           {
             case XmlNodeType.Element:
               Console.Write("<{0}>", reader.Name);
               break;
             case XmlNodeType.Text:
               Console.Write(reader.Value);
               break;
             case XmlNodeType.CDATA:
               Console.Write("<![CDATA[{0}]]>", reader.Value);
               break;
             case XmlNodeType.ProcessingInstruction:
               Console.Write("<?{0} {1}?>", reader.Name, reader.Value);
               break;
             case XmlNodeType.Comment:
               Console.Write("<!--{0}-->", reader.Value);
               break;
             case XmlNodeType.XmlDeclaration:
               Console.Write("<?xml version='1.0'?>");
               break;
             case XmlNodeType.Document:
               break;
             case XmlNodeType.DocumentType:
               Console.Write("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
               break;
             case XmlNodeType.EntityReference:
               Console.Write(reader.Name);
               break;
             case XmlNodeType.EndElement:
               Console.Write("</{0}>", reader.Name);
               break;
           }       
        }           
     }

     finally
     {
        if (reader!=null)
          reader.Close();
     }
  }

} // End class

    

The example uses the file, items.xml, as input.


<?xml version="1.0"?>
<!-- This is a sample XML document -->
<!DOCTYPE Items [<!ENTITY number "123">]>
<Items>
  <Item>Test with an entity: &number;</Item>
  <Item>test with a child element <more/> stuff</Item>
  <Item>test with a CDATA section <![CDATA[<456>]]> def</Item>
  <Item>Test with an char entity: &#65;</Item>
  <!-- Fourteen chars in this element.-->
  <Item>1234567890ABCD</Item>
</Items>

    

Return to top


Overloaded ctor #4
Summary
Initializes a new instance of the XmlTextReader class with the specified TextReader.
C# Syntax:
public XmlTextReader(
   TextReader input
);
Parameters:

input

The TextReader containing the XML data to read.

Remarks
It is assumed that the TextReader is already set to the correct encoding. This is used by clients that have already read some things from the stream in a multi-part MIME scenario.

Return to top


Overloaded ctor #5
Summary
Initializes a new instance of the XmlTextReader class with the specified XmlNameTable.
This type supports the Shared Source CLI infrastructure and is not intended to be used directly from your code.
C# Syntax:
protected XmlTextReader(
   XmlNameTable nt
);
Parameters:

nt

The XmlNameTable to use.

Return to top


Overloaded ctor #6
Summary
Initializes a new instance of the XmlTextReader class with the specified stream and XmlNameTable.
C# Syntax:
public XmlTextReader(
   Stream input,
   XmlNameTable nt
);
Parameters:

input

The stream containing the XML data to read.

nt

The XmlNameTable to use.

Exceptions
Exception Type Condition
NullReferenceException The nt value is null.
Remarks
The XmlTextReader decodes the stream using Encoding.

If you specify a name table, this constructor uses the names defined already in that table.

Return to top


Overloaded ctor #7
Summary
Initializes a new instance of the XmlTextReader class with the specified URL and stream.
C# Syntax:
public XmlTextReader(
   string url,
   Stream input
);
Parameters:

url

The URL to use for resolving external resources. The XmlTextReader.BaseURI is set to this value.

input

The stream containing the XML data to read.

Return to top


Overloaded ctor #8
Summary
Initializes a new instance of the XmlTextReader class with the specified URL and TextReader.
C# Syntax:
public XmlTextReader(
   string url,
   TextReader input
);
Parameters:

url

The URL to use for resolving external resources. The XmlTextReader.BaseURI is set to this value.

input

The TextReader containing the XML data to read.

Remarks
It is assumed that the TextReader is already set to the correct encoding. This is used by clients that have already read some things from the stream in a multi-part MIME scenario.

Return to top


Overloaded ctor #9
Summary
Initializes a new instance of the XmlTextReader class with the specified file and XmlNameTable.
C# Syntax:
public XmlTextReader(
   string url,
   XmlNameTable nt
);
Parameters:

url

The URL for the file containing the XML data to read.

nt

The XmlNameTable to use.

Exceptions
Exception Type Condition
NullReferenceException The nt value is null.

Return to top


Overloaded ctor #10
Summary
Initializes a new instance of the XmlTextReader class with the specified TextReader and XmlNameTable.
C# Syntax:
public XmlTextReader(
   TextReader input,
   XmlNameTable nt
);
Parameters:

input

The TextReader containing the XML data to read.

nt

The XmlNameTable to use.

Exceptions
Exception Type Condition
NullReferenceException The nt value is null.
Remarks
It is assumed that the TextReader is already set to the correct encoding. This is used by clients that have already read some things from the stream in a multi-part MIME scenario.

Return to top


Overloaded ctor #11
Summary
Initializes a new instance of the XmlTextReader class with the specified values.
C# Syntax:
public XmlTextReader(
   Stream xmlFragment,
   XmlNodeType fragType,
   XmlParserContext context
);
Parameters:

xmlFragment

The stream containing the XML fragment to parse.

fragType

The XmlNodeType of the XML fragment. This also determines what the fragment can contain. (See table below.)

context

The XmlParserContext in which the xmlFragment is to be parsed. This includes the XmlNameTable to use, encoding, namespace scope, the current xml:lang, and the xml:space scope. The XmlParserContext in which the xmlFragment is to be parsed. This includes the XmlNameTable to use, encoding, namespace scope, the current xml:lang, and the xml:space scope.

Exceptions
Exception Type Condition
XmlException fragType is not Element, Attribute, or Document.
Remarks
This constructor parses the given string as a fragment of XML. If the XML fragment is an element or attribute, you can bypass the root level rules for well-formed XML documents.

The following table lists valid values for fragType.



XmlNodeType Fragment May Contain
Element Any valid element content (for example, any combination of elements, comments, processing instructions, CDATA sections, text, and entity references).
Attribute The value of an attribute (the part inside the quotes).
Document The contents of an entire XML document. This will enforce document level rules.

The reader uses the following to determine the encoding of the stream.

  1. Checks the XmlParserContext.Encoding property to determine the encoding.
  2. If the Encoding property is null, the reader checks for a byte-order mark at the beginning of the stream.
  3. If the Encoding property is null, and no byte-order mark is found, the reader assumes the stream is encoded in UTF-8.

Return to top


Overloaded ctor #12
Summary
Initializes a new instance of the XmlTextReader class with the specified URL, stream and XmlNameTable.
C# Syntax:
public XmlTextReader(
   string url,
   Stream input,
   XmlNameTable nt
);
Parameters:

url

The URL to use for resolving external resources. The XmlTextReader.BaseURI is set to this value.

input

The stream containing the XML data to read.

nt

The XmlNameTable to use.

Exceptions
Exception Type Condition
NullReferenceException The nt value is null.

Return to top


Overloaded ctor #13
Summary
Initializes a new instance of the XmlTextReader class with the specified URL, TextReader and XmlNameTable.
C# Syntax:
public XmlTextReader(
   string url,
   TextReader input,
   XmlNameTable nt
);
Parameters:

url

The URL to use for resolving external resources. The XmlTextReader.BaseURI is set to this value.

input

The TextReader containing the XML data to read.

nt

The XmlNameTable to use.

Exceptions
Exception Type Condition
NullReferenceException The nt value is null.
Remarks
It is assumed that the TextReader is already set to the correct encoding. This is used by clients that have already read some things from the stream in a multi-part MIME scenario.

Return to top


Overloaded ctor #14
Summary
Initializes a new instance of the XmlTextReader class with the specified values.
C# Syntax:
public XmlTextReader(
   string xmlFragment,
   XmlNodeType fragType,
   XmlParserContext context
);
Parameters:

xmlFragment

The string containing the XML fragment to parse.

fragType

The XmlNodeType of the XML fragment. This also determines what the fragment string can contain. (See table below.)

context

The XmlParserContext in which the xmlFragment is to be parsed. This includes the XmlNameTable to use, encoding, namespace scope, the current xml:lang, and the xml:space scope. The XmlParserContext in which the xmlFragment is to be parsed. This includes the XmlNameTable to use, encoding, namespace scope, the current xml:lang, and the xml:space scope.

Exceptions
Exception Type Condition
XmlException fragType is not Element, Attribute, or Document.
Remarks
This constructor parses the given string as a fragment of XML. If the XML fragment is an element or attribute, you can bypass the root level rules for well-formed XML documents. This constructor can handle strings returned from XmlTextReader.ReadInnerXml.

The following table lists valid values for fragType and how the reader will parse each of the different node types.



XmlNodeType Fragment May Contain
Element Any valid element content (for example, any combination of elements, comments, processing instructions, CDATA sections, text, and entity references).
Attribute The value of an attribute (the part inside the quotes).
Document The contents of an entire XML document. This will enforce document level rules.
Example
The following example parses an XML fragment. It uses the XmlParserContext and its XmlNamespaceManager to handle namespace resolution.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {

    //Create the XML fragment to be parsed.
    string xmlFrag ="<book> " +
                         "<title>Pride And Prejudice</title>" +
                         "<bk:genre>novel</bk:genre>" +
                         "</book>"; 

    //Create the XmlNamespaceManager.
    NameTable nt = new NameTable();
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
    nsmgr.AddNamespace("bk", "urn:sample");

    //Create the XmlParserContext.
    XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);

    //Create the reader. 
    XmlTextReader reader = new XmlTextReader(xmlFrag, XmlNodeType.Element, context);
  
    //Parse the XML.  If they exist, display the prefix and  
    //namespace URI of each element.
    while (reader.Read()){
      if (reader.IsStartElement()){
        if (reader.Prefix==String.Empty)
           Console.WriteLine("<{0}>", reader.LocalName);
        else{
            Console.Write("<{0}:{1}>", reader.Prefix, reader.LocalName);
            Console.WriteLine(" The namespace URI is " + reader.NamespaceURI);
        }
      }
    }
  
    //Close the reader.
    reader.Close();     
  
  }
} // End class

    
See also:
XmlParserContext

Return to top


Overridden Property: AttributeCount (read-only)
Summary
Gets the number of attributes on the current node.
C# Syntax:
public override int AttributeCount {get;}
Remarks
This property is relevant to Element, DocumentType and XmlDeclaration nodes only. (Other node types do not have attributes.)
Example
The following example displays all attributes on the current node.
public void DisplayAttributes(XmlReader reader)
{
  if (reader.HasAttributes)
  {
    Console.WriteLine("Attributes of <" + reader.Name + ">");
    for (int i = 0; i < reader.AttributeCount; i++)
    {
      reader.MoveToAttribute(i);
      Console.Write(" {0}={1}", reader.Name, reader.Value);
    }
    reader.MoveToElement(); //Moves the reader back to the element node.
  }
}

    

Return to top


Overridden Property: BaseURI (read-only)
Summary
Gets the base URI of the current node.
C# Syntax:
public override string BaseURI {get;}
Remarks
A networked XML document is comprised of chunks of data aggregated using various W3C standard inclusion mechanisms and therefore contains nodes that come from different places. DTD entities are an example of this, but this is not limited to DTDs. The base URI tells you where these nodes came from. If there is no base URI for the nodes being returned (for example, they were parsed from an in-memory string), String.Empty is returned.
Example
The following example displays the base URI for each of the nodes.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {           
        //Load the reader with the XML file.
        reader = new XmlTextReader("http://localhost/baseuri.xml");

        //Parse the file and display the base URI for each node.
        while (reader.Read())
        {
            Console.WriteLine("({0}) {1}", reader.NodeType, reader.BaseURI);
         }           
     }

     finally
     {
       if (reader!=null)
         reader.Close();
     }
  }
} // End class

    
The example uses the file, baseuri.xml, as input.

<!-- XML fragment -->
<book genre="novel">
  <title>Pride And Prejudice</title>
</book>

    

Return to top


Property: CanResolveEntity (read-only)
Inherited
See base class member description: System.Xml.XmlReader.CanResolveEntity

Summary
Gets a value indicating whether this reader can parse and resolve entities.
C# Syntax:
public virtual bool CanResolveEntity {get;}
Remarks
This property always returns false for implementations of XmlReader that do not support DTD information. In this case, calling XmlReader.ResolveEntity throws an exception.

Return to top


Overridden Property: Depth (read-only)
Summary
Gets the depth of the current node in the XML document.
C# Syntax:
public override int Depth {get;}
Example
The following example displays each node including its depth, line number, and line position.
using System;
using System.IO;
using System.Xml;

public class Sample{

  public static void Main(){

    // Create the XML fragment to be parsed.
    string xmlFrag  = 
    @"<book> 
         <misc>
           <style>paperback</style> 
           <pages>240</pages>
         </misc> 
        </book>";

    // Create the XmlNamespaceManager.
    NameTable nt = new NameTable();
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);

    // Create the XmlParserContext.
    XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);

    // Create the reader.
    XmlTextReader reader = new XmlTextReader(xmlFrag, XmlNodeType.Element, context);

    // Parse the XML and display each node.
    while (reader.Read()){
       switch (reader.NodeType){
         case XmlNodeType.Element:
           Console.Write("{0} {1},{2}  ", reader.Depth, reader.LineNumber, reader.LinePosition);
           Console.WriteLine("<{0}>", reader.Name);
           break;
         case XmlNodeType.Text:
           Console.Write("{0} {1},{2}  ", reader.Depth, reader.LineNumber, reader.LinePosition);
           Console.WriteLine("  {0}", reader.Value);
           break;
         case XmlNodeType.EndElement:
           Console.Write("{0} {1},{2}  ", reader.Depth, reader.LineNumber, reader.LinePosition);
           Console.WriteLine("</{0}>", reader.Name);
           break;
       }       
    }           

    // Close the reader.
    reader.Close();      
  }
}

    

Return to top


Property: Encoding (read-only)
Summary
Gets the encoding of the document.
C# Syntax:
public Encoding Encoding {get;}
Remarks
All encoding standards supported by the underlying operating system are supported.

Return to top


Overridden Property: EOF (read-only)
Summary
Gets a value indicating whether the reader is positioned at the end of the stream.
C# Syntax:
public override bool EOF {get;}

Return to top


Property: HasAttributes (read-only)
Inherited
See base class member description: System.Xml.XmlReader.HasAttributes

Summary
Gets a value indicating whether the current node has any attributes.
C# Syntax:
public virtual bool HasAttributes {get;}
Example
The following example displays all attributes on the current node.
    public void DisplayAttributes(XmlReader reader)
    {
        if (reader.HasAttributes)
        {
            Console.WriteLine("Attributes of <" + reader.Name + ">");
            while (reader.MoveToNextAttribute())
            {
                Console.WriteLine(" {0}={1}", reader.Name, reader.Value);
            }
        }
    }

    

Return to top


Overridden Property: HasValue (read-only)
Summary
Gets a value indicating whether the current node can have a XmlTextReader.Value.
C# Syntax:
public override bool HasValue {get;}
Remarks
The following table lists node types that have a value to return.

Node Type Value
Attribute The value of the attribute.
CDATA The content of the CDATA section.
Comment The content of the comment.
DocumentType The internal subset.
ProcessingInstruction The entire content, excluding the target.
SignificantWhitespace The white space between markup in a mixed content model.
Text The content of the text node.
Whitespace The white space between markup.
XmlDeclaration The content of the declaration.
Example
The following example displays the value for every node that can have a value.
using System;
using System.IO;
using System.Xml;

public class Sample
{

  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {           
        //Load the reader with the XML file.
        reader = new XmlTextReader("book1.xml");
        reader.WhitespaceHandling = WhitespaceHandling.None;

        //Parse the file and display each node.
        while (reader.Read())
        {
           if (reader.HasValue)
             Console.WriteLine("({0})  {1}={2}", reader.NodeType, reader.Name, reader.Value);
           else
             Console.WriteLine("({0}) {1}", reader.NodeType, reader.Name);
         }           
     }

     finally
     {
       if (reader!=null)
         reader.Close();
     }
  }
} // End class

    
The example uses the file, book1.xml, as input.

<?xml version='1.0' ?>
<!DOCTYPE book [<!ENTITY h 'hardcover'>]>
<book>
  <title>Pride And Prejudice</title>
  <misc>&h;</misc>
</book>

    

Return to top


Overridden Property: IsDefault (read-only)
Summary
Gets a value indicating whether the current node is an attribute that was generated from the default value defined in the DTD or schema.
C# Syntax:
public override bool IsDefault {get;}
Remarks
This property applies only to attribute nodes.

Return to top


Overridden Property: IsEmptyElement (read-only)
Summary
Gets a value indicating whether the current node is an empty element (for example, <MyElement/> ).
C# Syntax:
public override bool IsEmptyElement {get;}
Remarks
This property enables you to determine the difference between the following:

<item bar="123"/> (IsEmptyElement is true).

<item bar="123"> (IsEmptyElement is false).

A corresponding EndElement node is not generated for empty elements.

Example
The following example displays the text content of each element.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {
       //Load the reader with the XML file.
       reader = new XmlTextReader("elems.xml");
  
       //Parse the XML and display the text content of each of the elements.
       while (reader.Read()){
         if (reader.IsStartElement()){
           if (reader.IsEmptyElement)
              Console.WriteLine("<{0}/>", reader.Name);
           else{
               Console.Write("<{0}> ", reader.Name);
               reader.Read(); //Read the start tag.
               if (reader.IsStartElement())  //Handle nested elements.
                 Console.Write("\r\n<{0}>", reader.Name);
               Console.WriteLine(reader.ReadString());  //Read the text content of the element.
           }
         }
       } 
       
     } 

     finally 
     {
        if (reader != null)
          reader.Close();
      }
  }
  
} // End class

    
The example uses the file, elems.xml, as input.

<book>
  <title>Pride And Prejudice</title>
  <price>19.95</price>
  <misc/>
</book>

    

Return to top


Overloaded Property: Item (read-only)
Summary
Gets the value of the attribute with the specified index.
C# Syntax:
public override string this[int i] {get;}
Parameters:

i

The index of the attribute.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException The i parameter is less than 0 or greater than or equal to XmlTextReader.AttributeCount.
Remarks
This property does not move the reader.
Example
The following example displays all attributes on the current node.
public void DisplayAttributes(XmlReader reader)
{
    if (reader.HasAttributes)
    {
        Console.WriteLine("Attributes of <" + reader.Name + ">");
        for (int i = 0; i < reader.AttributeCount; i++)
        {
            Console.WriteLine("  {0}", reader[i]);
        }
    }
}

    
See also:
XmlTextReader.GetAttribute

Return to top


Overloaded Property: Item (read-only)
Summary
Gets the value of the attribute with the specified name.
C# Syntax:
public override string this[string name] {get;}
Parameters:

name

The qualified name of the attribute.

Remarks
This property does not move the reader.

If the reader is positioned on a DocumentType node, this method can be used to get the PUBLIC and SYSTEM literals, for example, reader["PUBLIC"]

Example
The following example gets the value of the ISBN attribute.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {
       //Load the reader with the XML file.
       reader = new XmlTextReader("attrs.xml");
  
       //Read the ISBN attribute.
       reader.MoveToContent();
       string isbn =reader["ISBN"];
       Console.WriteLine("The ISBN value: " + isbn);

     } 
     finally 
     {
        if (reader != null)
          reader.Close();
      }
  }
  
} // End class

    
The example uses the file, attrs.xml, as input.

<book genre='novel' ISBN='1-861003-78' pubdate='1987'>
</book>

    
See also:
XmlTextReader.GetAttribute

Return to top


Overloaded Property: Item (read-only)
Summary
Gets the value of the attribute with the specified local name and namespace URI.
C# Syntax:
public override string this[string name, string namespaceURI] {get;}
Parameters:

name

The local name of the attribute.

namespaceURI

The namespace URI of the attribute.

Remarks
This property does not move the reader.
See also:
XmlTextReader.GetAttribute

Return to top


Property: LineNumber (read-only)
Summary
Gets the current line number.
C# Syntax:
public int LineNumber {get;}
Implements:
IXmlLineInfo.LineNumber
Remarks
This property is most commonly used for error reporting, but can be called at any time. The starting value for this property is 1.

Combined with XmlTextReader.LinePosition, a value of 1,1 indicates the start of the document.

Example
The following example displays each node including its depth, line number, and line position.
using System;
using System.IO;
using System.Xml;

public class Sample{

  public static void Main(){

    // Create the XML fragment to be parsed.
    string xmlFrag  = 
    @"<book> 
         <misc>
           <style>paperback</style> 
           <pages>240</pages>
         </misc> 
        </book>";

    // Create the XmlNamespaceManager.
    NameTable nt = new NameTable();
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);

    // Create the XmlParserContext.
    XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);

    // Create the reader.
    XmlTextReader reader = new XmlTextReader(xmlFrag, XmlNodeType.Element, context);

    // Parse the XML and display each node.
    while (reader.Read()){
       switch (reader.NodeType){
         case XmlNodeType.Element:
           Console.Write("{0} {1},{2}  ", reader.Depth, reader.LineNumber, reader.LinePosition);
           Console.WriteLine("<{0}>", reader.Name);
           break;
         case XmlNodeType.Text:
           Console.Write("{0} {1},{2}  ", reader.Depth, reader.LineNumber, reader.LinePosition);
           Console.WriteLine("  {0}", reader.Value);
           break;
         case XmlNodeType.EndElement:
           Console.Write("{0} {1},{2}  ", reader.Depth, reader.LineNumber, reader.LinePosition);
           Console.WriteLine("</{0}>", reader.Name);
           break;
       }       
    }           

    // Close the reader.
    reader.Close();      
  }
}

    

Return to top


Property: LinePosition (read-only)
Summary
Gets the current line position.
C# Syntax:
public int LinePosition {get;}
Implements:
IXmlLineInfo.LinePosition
Remarks
This property is most commonly used for error reporting, but can be called at any time. The property's starting value is 1.

The position indicated is the first character of text in the markup.

              <root>
              abc<tag/>
              </root>
            

On the first line of the preceding XML text, a LinePosition of 2 corresponds to the character r ; on the second line, a LinePosition of 5 corresponds to the character t ; and on the third line, a LinePosition of 3 corresponds to the character r .

Combined with XmlTextReader.LineNumber, a value of 1,1 indicates the start of the document.

Example
The following example displays each node including its depth, line number, and line position.
using System;
using System.IO;
using System.Xml;

public class Sample{

  public static void Main(){

    // Create the XML fragment to be parsed.
    string xmlFrag  = 
    @"<book> 
         <misc>
           <style>paperback</style> 
           <pages>240</pages>
         </misc> 
        </book>";

    // Create the XmlNamespaceManager.
    NameTable nt = new NameTable();
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);

    // Create the XmlParserContext.
    XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);

    // Create the reader.
    XmlTextReader reader = new XmlTextReader(xmlFrag, XmlNodeType.Element, context);

    // Parse the XML and display each node.
    while (reader.Read()){
       switch (reader.NodeType){
         case XmlNodeType.Element:
           Console.Write("{0} {1},{2}  ", reader.Depth, reader.LineNumber, reader.LinePosition);
           Console.WriteLine("<{0}>", reader.Name);
           break;
         case XmlNodeType.Text:
           Console.Write("{0} {1},{2}  ", reader.Depth, reader.LineNumber, reader.LinePosition);
           Console.WriteLine("  {0}", reader.Value);
           break;
         case XmlNodeType.EndElement:
           Console.Write("{0} {1},{2}  ", reader.Depth, reader.LineNumber, reader.LinePosition);
           Console.WriteLine("</{0}>", reader.Name);
           break;
       }       
    }           

    // Close the reader.
    reader.Close();      
  }
}

    

Return to top


Overridden Property: LocalName (read-only)
Summary
Gets the local name of the current node.
C# Syntax:
public override string LocalName {get;}
Example
The following example displays the local name of each node, and, if they exist, the prefix and namespace URI.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {

       //Load the reader with the XML file.
       reader = new XmlTextReader("book2.xml");
  
       //Parse the file.  If they exist, display the prefix and 
       //namespace URI of each node.
       while (reader.Read()){
         if (reader.IsStartElement()){
           if (reader.Prefix==String.Empty)
              Console.WriteLine("<{0}>", reader.LocalName);
           else{
               Console.Write("<{0}:{1}>", reader.Prefix, reader.LocalName);
               Console.WriteLine(" The namespace URI is " + reader.NamespaceURI);
           }
         }
       }       

     } 
     finally 
     {
        if (reader != null)
          reader.Close();
      }
  }  
} // End class

    
The example uses the file, book2.xml, as input.

<book xmlns:bk='urn:samples'>
  <title>Pride And Prejudice</title>
  <bk:genre>novel</bk:genre>
</book>

    

Return to top


Overridden Property: Name (read-only)
Summary
Gets the qualified name of the current node.
C# Syntax:
public override string Name {get;}
Example
The following example reads an XML file and displays each of the nodes.


using System;
using System.IO;
using System.Xml;

//Reads an XML document

public class Sample
{
  private const String filename = "items.xml";

  public static void Main()
  {
     XmlTextReader reader = null;

     try
     {  
        //Load the reader with the data file and ignore all white space nodes.         
        reader = new XmlTextReader(filename);
        reader.WhitespaceHandling = WhitespaceHandling.None;

        //Parse the file and display each of the nodes.
        while (reader.Read())
        {
           switch (reader.NodeType)
           {
             case XmlNodeType.Element:
               Console.Write("<{0}>", reader.Name);
               break;
             case XmlNodeType.Text:
               Console.Write(reader.Value);
               break;
             case XmlNodeType.CDATA:
               Console.Write("<![CDATA[{0}]]>", reader.Value);
               break;
             case XmlNodeType.ProcessingInstruction:
               Console.Write("<?{0} {1}?>", reader.Name, reader.Value);
               break;
             case XmlNodeType.Comment:
               Console.Write("<!--{0}-->", reader.Value);
               break;
             case XmlNodeType.XmlDeclaration:
               Console.Write("<?xml version='1.0'?>");
               break;
             case XmlNodeType.Document:
               break;
             case XmlNodeType.DocumentType:
               Console.Write("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
               break;
             case XmlNodeType.EntityReference:
               Console.Write(reader.Name);
               break;
             case XmlNodeType.EndElement:
               Console.Write("</{0}>", reader.Name);
               break;
           }       
        }           
     }

     finally
     {
        if (reader!=null)
          reader.Close();
     }
  }

} // End class

    

The sample uses the file items.xml.


<?xml version="1.0"?>
<!-- This is a sample XML document -->
<!DOCTYPE Items [<!ENTITY number "123">]>
<Items>
  <Item>Test with an entity: &number;</Item>
  <Item>test with a child element <more/> stuff</Item>
  <Item>test with a CDATA section <![CDATA[<456>]]> def</Item>
  <Item>Test with an char entity: &#65;</Item>
  <!-- Fourteen chars in this element.-->
  <Item>1234567890ABCD</Item>
</Items>

    

Return to top


Property: Namespaces (read-write)
Summary
Gets or sets a value indicating whether to do namespace support.
C# Syntax:
public bool Namespaces {get; set;}
Exceptions
Exception Type Condition
InvalidOperationException Setting this property after a read operation has occurred ( XmlTextReader.ReadState is not ReadState.Initial).
Remarks
This property determines whether the reader supports the W3C Namespaces in XML recommendation located at www.w3.org/TR/REC-xml-names.

The Namespaces property cannot be set after a read operation has occurred.

Return to top


Overridden Property: NamespaceURI (read-only)
Summary
Gets the namespace URI (as defined in the W3C Namespace specification) of the node on which the reader is positioned.
C# Syntax:
public override string NamespaceURI {get;}
Remarks
This property is relevant to Element and Attribute nodes only.
Example
The following example displays the local name of each node, and, if they exist, the prefix and namespace URI.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {

       //Load the reader with the XML file.
       reader = new XmlTextReader("book2.xml");
  
       //Parse the file.  If they exist, display the prefix and 
       //namespace URI of each node.
       while (reader.Read()){
         if (reader.IsStartElement()){
           if (reader.Prefix==String.Empty)
              Console.WriteLine("<{0}>", reader.LocalName);
           else{
               Console.Write("<{0}:{1}>", reader.Prefix, reader.LocalName);
               Console.WriteLine(" The namespace URI is " + reader.NamespaceURI);
           }
         }
       }       

     } 
     finally 
     {
        if (reader != null)
          reader.Close();
      }
  }  
} // End class

    
The example uses the file, book2.xml, as input.

<book xmlns:bk='urn:samples'>
  <title>Pride And Prejudice</title>
  <bk:genre>novel</bk:genre>
</book>

    

Return to top


Overridden Property: NameTable (read-only)
Summary
Gets the XmlNameTable associated with this implementation.
C# Syntax:
public override XmlNameTable NameTable {get;}
Remarks
All node and attribute names returned from this class are atomized using the NameTable. When the same name is returned multiple times (for example, Customer), then the same String object will be returned for that name. This makes it possible for you to write efficient code that does object comparisons on these strings instead of expensive string comparisons.
See also:
XmlNameTable

Return to top


Overridden Property: NodeType (read-only)
Summary
Gets the type of the current node.
C# Syntax:
public override XmlNodeType NodeType {get;}
Remarks
This property never returns the following XmlNodeType types: Document, DocumentFragment, Entity, EndEntity, or Notation.
Example
The following example reads an XML file and displays each of the nodes.


using System;
using System.IO;
using System.Xml;

//Reads an XML document

public class Sample
{
  private const String filename = "items.xml";

  public static void Main()
  {
     XmlTextReader reader = null;

     try
     {  
        //Load the reader with the data file and ignore all white space nodes.         
        reader = new XmlTextReader(filename);
        reader.WhitespaceHandling = WhitespaceHandling.None;

        //Parse the file and display each of the nodes.
        while (reader.Read())
        {
           switch (reader.NodeType)
           {
             case XmlNodeType.Element:
               Console.Write("<{0}>", reader.Name);
               break;
             case XmlNodeType.Text:
               Console.Write(reader.Value);
               break;
             case XmlNodeType.CDATA:
               Console.Write("<![CDATA[{0}]]>", reader.Value);
               break;
             case XmlNodeType.ProcessingInstruction:
               Console.Write("<?{0} {1}?>", reader.Name, reader.Value);
               break;
             case XmlNodeType.Comment:
               Console.Write("<!--{0}-->", reader.Value);
               break;
             case XmlNodeType.XmlDeclaration:
               Console.Write("<?xml version='1.0'?>");
               break;
             case XmlNodeType.Document:
               break;
             case XmlNodeType.DocumentType:
               Console.Write("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
               break;
             case XmlNodeType.EntityReference:
               Console.Write(reader.Name);
               break;
             case XmlNodeType.EndElement:
               Console.Write("</{0}>", reader.Name);
               break;
           }       
        }           
     }

     finally
     {
        if (reader!=null)
          reader.Close();
     }
  }

} // End class

    

The sample uses the file items.xml.


<?xml version="1.0"?>
<!-- This is a sample XML document -->
<!DOCTYPE Items [<!ENTITY number "123">]>
<Items>
  <Item>Test with an entity: &number;</Item>
  <Item>test with a child element <more/> stuff</Item>
  <Item>test with a CDATA section <![CDATA[<456>]]> def</Item>
  <Item>Test with an char entity: &#65;</Item>
  <!-- Fourteen chars in this element.-->
  <Item>1234567890ABCD</Item>
</Items>

    

Return to top


Property: Normalization (read-write)
Summary
Gets or sets a value indicating whether to normalize white space and attribute values.
C# Syntax:
public bool Normalization {get; set;}
Remarks
This property can be changed at any time and takes effect on the next read operation.

Note If the XmlTextReader is used to construct an XmlValidatingReader, to normalize attribute values, Normalization must be set to true.

If Normalization is set to false, this also disables character range checking for numeric entities. As a result, character entities, such as &#0; , are allowed.

The following describes attribute value normalization:

Refer to the W3C XML 1.0 recommendation for further discussion on normalization.

Example
The following example shows reader behavior with normalization turned on and then off.
using System;
using System.IO;
using System.Xml;

public class Sample{

  public static void Main(){

    // Create the XML fragment to be parsed.
    string xmlFrag  = 
    @"<item attr1='  test A B C
           1 2 3'/>
        <item attr2='&#01;'/>";                         

    // Create the XmlNamespaceManager.
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());

    // Create the XmlParserContext.
    XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.Preserve);

    // Create the reader.
    XmlTextReader reader = new XmlTextReader(xmlFrag, XmlNodeType.Element, context);

    // Show attribute value normalization.
    reader.Read();
    reader.Normalization = false;
    Console.WriteLine("Attribute value:{0}", reader.GetAttribute("attr1"));
    reader.Normalization = true;
    Console.WriteLine("Attribute value:{0}", reader.GetAttribute("attr1"));

    // Set Normalization back to false.  This allows the reader to accept
    // character entities in the &#00; to &#20; range.  If Normalization had
    // been set to true, character entities in this range throw an exception.
    reader.Normalization = false;
    reader.Read();
    reader.MoveToContent();
    Console.WriteLine("Attribute value:{0}", reader.GetAttribute("attr2"));
  
    // Close the reader.
    reader.Close();     
  
  }
}

    

Return to top


Overridden Property: Prefix (read-only)
Summary
Gets the namespace prefix associated with the current node.
C# Syntax:
public override string Prefix {get;}
Example
The following example displays the local name of each node, and, if they exist, the prefix and namespace URI.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {

       //Load the reader with the XML file.
       reader = new XmlTextReader("book2.xml");
  
       //Parse the file.  If they exist, display the prefix and 
       //namespace URI of each node.
       while (reader.Read()){
         if (reader.IsStartElement()){
           if (reader.Prefix==String.Empty)
              Console.WriteLine("<{0}>", reader.LocalName);
           else{
               Console.Write("<{0}:{1}>", reader.Prefix, reader.LocalName);
               Console.WriteLine(" The namespace URI is " + reader.NamespaceURI);
           }
         }
       }       

     } 
     finally 
     {
        if (reader != null)
          reader.Close();
      }
  }  
} // End class

    
The example uses the file, book2.xml, as input.

<book xmlns:bk='urn:samples'>
  <title>Pride And Prejudice</title>
  <bk:genre>novel</bk:genre>
</book>

    

Return to top


Overridden Property: QuoteChar (read-only)
Summary
Gets the quotation mark character used to enclose the value of an attribute node.
C# Syntax:
public override char QuoteChar {get;}
Remarks
This property applies only to an attribute node.

Return to top


Overridden Property: ReadState (read-only)
Summary
Gets the state of the reader.
C# Syntax:
public override ReadState ReadState {get;}

Return to top


Overridden Property: Value (read-only)
Summary
Gets the text value of the current node.
C# Syntax:
public override string Value {get;}
Example
The following example reads an XML file and displays each node.


using System;
using System.IO;
using System.Xml;

//Reads an XML document

public class Sample
{
  private const String filename = "items.xml";

  public static void Main()
  {
     XmlTextReader reader = null;

     try
     {  
        //Load the reader with the data file and ignore all white space nodes.         
        reader = new XmlTextReader(filename);
        reader.WhitespaceHandling = WhitespaceHandling.None;

        //Parse the file and display each of the nodes.
        while (reader.Read())
        {
           switch (reader.NodeType)
           {
             case XmlNodeType.Element:
               Console.Write("<{0}>", reader.Name);
               break;
             case XmlNodeType.Text:
               Console.Write(reader.Value);
               break;
             case XmlNodeType.CDATA:
               Console.Write("<![CDATA[{0}]]>", reader.Value);
               break;
             case XmlNodeType.ProcessingInstruction:
               Console.Write("<?{0} {1}?>", reader.Name, reader.Value);
               break;
             case XmlNodeType.Comment:
               Console.Write("<!--{0}-->", reader.Value);
               break;
             case XmlNodeType.XmlDeclaration:
               Console.Write("<?xml version='1.0'?>");
               break;
             case XmlNodeType.Document:
               break;
             case XmlNodeType.DocumentType:
               Console.Write("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
               break;
             case XmlNodeType.EntityReference:
               Console.Write(reader.Name);
               break;
             case XmlNodeType.EndElement:
               Console.Write("</{0}>", reader.Name);
               break;
           }       
        }           
     }

     finally
     {
        if (reader!=null)
          reader.Close();
     }
  }

} // End class

    

The sample uses the file items.xml.


<?xml version="1.0"?>
<!-- This is a sample XML document -->
<!DOCTYPE Items [<!ENTITY number "123">]>
<Items>
  <Item>Test with an entity: &number;</Item>
  <Item>test with a child element <more/> stuff</Item>
  <Item>test with a CDATA section <![CDATA[<456>]]> def</Item>
  <Item>Test with an char entity: &#65;</Item>
  <!-- Fourteen chars in this element.-->
  <Item>1234567890ABCD</Item>
</Items>

    

Return to top


Property: WhitespaceHandling (read-write)
Summary
Gets or sets a value that specifies how white space is handled.
C# Syntax:
public WhitespaceHandling WhitespaceHandling {get; set;}
Exceptions
Exception Type Condition
ArgumentOutOfRangeException Invalid value specified.
InvalidOperationException Setting this property when the reader is closed ( XmlTextReader.ReadState is ReadState.Closed.
Remarks
This property can be changed at any time and takes effect on the next read operation.

Because the XmlTextReader does not have DTD information available to it, SignificantWhitepsace nodes are only returned within the an xml:space='preserve' scope.

Example
The following example reads an XML fragment.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main(){

    //Create the XML fragment to be parsed.
    string xmlFrag ="<book> " +
                    "  <title>Pride And Prejudice</title>" +
                    "  <genre>novel</genre>" +
                    "</book>"; 

    //Create the XmlNamespaceManager.
    NameTable nt = new NameTable();
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);

    //Create the XmlParserContext.
    XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.Default);

    Console.WriteLine("Read the XML and ignore all white space...");
    ReadXML(context, xmlFrag, WhitespaceHandling.None);

    Console.WriteLine("\r\nRead the XML including white space nodes...");
    ReadXML(context, xmlFrag, WhitespaceHandling.All);

  }
  
  public static void ReadXML(XmlParserContext context, string xmlFrag, WhitespaceHandling ws){

    //Create the reader and specify the WhitespaceHandling setting.
    XmlTextReader reader = new XmlTextReader(xmlFrag, XmlNodeType.Element, context);
    reader.WhitespaceHandling = ws;

      //Parse the XML and display each of the nodes.
      while (reader.Read())
      {
         switch (reader.NodeType)
         {
           case XmlNodeType.Element:
             Console.WriteLine("{0}: <{1}>", reader.NodeType, reader.Name);
             break;
           case XmlNodeType.Text:
             Console.WriteLine("{0}: {1}", reader.NodeType, reader.Value);
             break;
           case XmlNodeType.EndElement:
             Console.WriteLine("{0}: </{1}>", reader.NodeType, reader.Name);
             break;
           case XmlNodeType.Whitespace:
             Console.WriteLine("{0}:", reader.NodeType);
             break;
           case XmlNodeType.SignificantWhitespace:
             Console.WriteLine("{0}:", reader.NodeType);
             break;
         }       
      }           
  
    //Close the reader.
    reader.Close();     
  
  }
} // End class


    

Return to top


Overridden Property: XmlLang (read-only)
Summary
Gets the current xml:lang scope.
C# Syntax:
public override string XmlLang {get;}
Remarks
This property represents the xml:lang scope within which the current node resides. For example, here is an XML fragment with xml:lang set to US English in the root element:

<root xml:lang="en-us">

<name>Fred</name>

</root>

When the reader is positioned on the name element, you can use this property to find that it is in the scope of a US English xml:lang attribute.

The string returned is also in XmlTextReader.NameTable.

Example
The following example displays the xml:lang value for each of the nodes.
using System;
using System.IO;
using System.Xml;

public class Sample{

  public static void Main(){

    //Create the XML fragment to be parsed.
    string xmlFrag  = "<book xml:lang='en-US'> " +
                           "  <title xml:lang='en-GB'>Colour Analysis</title>" +
                           "  <title>Color Analysis</title>" +
                           "</book>"; 

    //Create the XmlNamespaceManager.
    NameTable nt = new NameTable();
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);

    //Create the XmlParserContext.
    XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);

    //Create the reader.
    XmlTextReader reader = new XmlTextReader(xmlFrag, XmlNodeType.Element, context);
    reader.WhitespaceHandling = WhitespaceHandling.None;

    //Parse the XML and display each of the nodes, including the xml:lang setting.
    while (reader.Read()){
       switch (reader.NodeType){
         case XmlNodeType.Element:
           Console.WriteLine("{0}: <{1}>", reader.XmlLang, reader.Name);
           break;
         case XmlNodeType.Text:
           Console.WriteLine("{0}: {1}", reader.XmlLang, reader.Value);
           break;
         case XmlNodeType.EndElement:
           Console.WriteLine("{0}: </{1}>", reader.XmlLang, reader.Name);
           break;
       }       
    }           
  
    //Close the reader.
    reader.Close();     
  
  }
}

    

Return to top


Property: XmlResolver (write-only)
Summary
Sets the XmlResolver used for resolving DTD references.
C# Syntax:
XmlResolver XmlResolver {set;}
Remarks
The reader uses XmlResolver to resolve the location of the file loaded into the reader and also to resolve DTD references. For example, if your XML included the DOCTYPE declaration, <!DOCTYPE book SYSTEM book.dtd> the reader resolves this external file and ensures that the DTD is well-formed. The reader does not use the DTD for validation.

If this property is not set, the reader uses the XmlUrlResolver with default credentials (Credentials.DefaultCredentials). However, if you have implemented a custom XmlResolver, you can specify the use of your custom XmlResolver instead.

This property can be changed at any time and takes effect on the next read operation. If this property is set to null, any external DTD or entities encountered by the reader are not resolved.

Return to top


Overridden Property: XmlSpace (read-only)
Summary
Gets the current xml:space scope.
C# Syntax:
public override XmlSpace XmlSpace {get;}
Example
The following example parses a file and returns significant white space if an xml:space='preserve' scope is found.
using System;
using System.IO;
using System.Xml;

public class Sample{

  public static void Main(){

     XmlTextReader reader = new XmlTextReader("authors.xml");
     reader.WhitespaceHandling = WhitespaceHandling.None;

     // Parse the file.  Return white space only if an
     // xml:space='preserve' attribute is found.
     while (reader.Read()){
       switch (reader.NodeType){
         case XmlNodeType.Element:
           Console.Write("<{0}>", reader.Name);
           if (reader.XmlSpace==XmlSpace.Preserve)
             reader.WhitespaceHandling=WhitespaceHandling.Significant;
           break;
         case XmlNodeType.Text:
           Console.Write(reader.Value);
           break;
         case XmlNodeType.EndElement:
           Console.Write("</{0}>", reader.Name);
           break;
         case XmlNodeType.SignificantWhitespace:
           Console.Write(reader.Value);
           break;         
       }              
     }
  }
}

    
The example uses the file, authors.xml, as input.
<book  xml:space='preserve'>
  <title>Color Analysis</title>
  <authors>
    <first>Michael</first> <last>Dunn</last>
    <first>Kim</first> <last>Akers</last>
  </authors>
</book>

    

Return to top


Overridden Method: Close()
Summary
Changes the XmlReader.ReadState to Closed.
C# Syntax:
public override void Close();
Remarks
This method also releases any resources held while reading. If this reader was constructed using a stream, this method also calls Close on the underlying stream.

If Close has already been called, no action is performed.

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~XmlTextReader();

For more information on members inherited from System.Object click on the link above.

Return to top


Overloaded Method: GetAttribute(
   int i
)
Summary
Gets the value of the attribute with the specified index.
C# Syntax:
public override string GetAttribute(
   int i
);
Parameters:

i

The index of the attribute. The index is zero-based. (The first attribute has index 0.)

Return Value:
The value of the specified attribute.
Exceptions
Exception Type Condition
ArgumentOutOfRangeException The i parameter is less than 0 or greater than or equal to XmlTextReader.AttributeCount.
Remarks
This method does not move the reader.

Return to top


Overloaded Method: GetAttribute(
   string name
)
Summary
Gets the value of the attribute with the specified name.
C# Syntax:
public override string GetAttribute(
   string name
);
Parameters:

name

The qualified name of the attribute.

Return Value:
The value of the specified attribute. If the attribute is not found, String.Empty is returned.
Remarks
This method does not move the reader.

If the reader is positioned on a DocumentType node, this method can be used to get the PUBLIC and SYSTEM literals, for example, reader.GetAttribute("PUBLIC")

Example
The following example gets the value of the ISBN attribute.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {
       //Load the reader with the XML file.
       reader = new XmlTextReader("attrs.xml");
  
       //Read the ISBN attribute.
       reader.MoveToContent();
       string isbn = reader.GetAttribute("ISBN");
       Console.WriteLine("The ISBN value: " + isbn);

     } 
     finally 
     {
        if (reader != null)
          reader.Close();
      }
  }
  
} // End class

    
The example uses the file, attrs.xml, as input.

<book genre='novel' ISBN='1-861003-78' pubdate='1987'>
</book>

    

Return to top


Overloaded Method: GetAttribute(
   string localName,
   string namespaceURI
)
Summary
Gets the value of the attribute with the specified local name and namespace URI.
C# Syntax:
public override string GetAttribute(
   string localName,
   string namespaceURI
);
Parameters:

localName

The local name of the attribute.

namespaceURI

The namespace URI of the attribute.

Return Value:
The value of the specified attribute. If the attribute is not found, String.Empty is returned. This method does not move the reader.
Remarks
The following XML contains an attribute in a specific namespace:

<test xmlns:dt="urn:datatypes" dt:type="int"/>

You can lookup the dt:type attribute using one argument (prefix and local name) or two arguments (local name and namespace URI):

String dt = reader.GetAttribute("dt:type");

String dt2 = reader.GetAttribute("type","urn:datatypes");

To lookup the xmlns:dt attribute, use one of the following arguments:

String dt3 = reader.GetAttribute("xmlns:dt");

String dt4 = reader.GetAttribute("dt",http://www.w3.org/2000/xmlns/);

You can also get this information using the XmlTextReader.Prefix property.

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetRemainder()
Summary
Gets the remainder of the buffered XML.
C# Syntax:
public TextReader GetRemainder();
Return Value:
A TextReader containing the remainder of the buffered XML.
Remarks
Because XmlTextReader does a buffered Read, it must be able to return the remainder of the unused buffer so that no data is lost. This allows protocols (such as multi-part MIME) to package XML in the same stream as other things.

After calling this method, XmlTextReader.EOF is set to true.

Example
The following example reads the first part of an XML document and then uses GetRemainder to complete reading the document using a second reader.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private static string filename = "tworeads.xml";
   
  public static void Main(string[] args)
  {
    XmlTextReader reader = new XmlTextReader(filename);
    reader.WhitespaceHandling=WhitespaceHandling.None;

    //Read the first part of the XML document
    while(reader.Read())
    {
     //Display the elements and stop reading on the book endelement tag
     //then go to ReadPart2 to start another reader to read the rest of the file. 
     switch(reader.NodeType)
     {
       case XmlNodeType.Element:
        Console.WriteLine("Name: {0}", reader.Name);
        break;
       case XmlNodeType.Text:
        Console.WriteLine("  Element Text: {0}", reader.Value);
        break;
       case XmlNodeType.EndElement:
        //Stop reading when the reader gets to the end element of the book node.
        if ("book"==reader.LocalName)
        {
          Console.WriteLine("End reading first book...");
          Console.WriteLine();      
          goto ReadPart2;
        }
        break;
     } 
    } 

    //Read the rest of the XML document
    ReadPart2:
    Console.WriteLine("Begin reading second book...");

    //Create a new reader to read the rest of the document.
    XmlTextReader reader2 = new XmlTextReader(reader.GetRemainder());

    while(reader2.Read())
    {
      switch (reader2.NodeType)
      {
        case XmlNodeType.Element:
         Console.WriteLine("Name: {0}", reader2.Name);
         break;
        case XmlNodeType.Text:
         Console.WriteLine("  Element Text: {0}", reader2.Value);
         break;
        case XmlNodeType.EndElement:
         //Stop reading when the reader gets to the end element of the book node.
         if ("book"==reader2.LocalName)
         {
           Console.WriteLine("End reading second book...");
           goto Done;
         }
         break;
      }
    }

    Done:
    Console.WriteLine("Done.");
    reader.Close(); 
    reader2.Close();
  }
}//End class

    

The example uses the input file tworeads.xml

<?xml version="1.0" ?>
<bookstore>
 <book>
  <title>Pride And Prejudice</title>
  <author>Jane Austen</author>
 </book>
 <book>
  <title>The Handmaid's Tale</title>
  <author>Margaret Atwood</author>
 </book>
</bookstore>

    

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Overloaded Method: IsStartElement()
Inherited
See base class member description: System.Xml.XmlReader.IsStartElement

Summary
Calls XmlReader.MoveToContent and tests if the current content node is a start tag or empty element tag.
C# Syntax:
public virtual bool IsStartElement();
Return Value:
true if MoveToContent finds a start tag or empty element tag; false if a node type other than XmlNodeType.Element was found.
Exceptions
Exception Type Condition
XmlException Incorrect XML is encountered in the input stream.
Remarks
This method skips white space, comments, and processing instructions until the reader is positioned on a content node. The method then tests if the current node is an element.
Example
The following example displays the text content of each element.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {
       //Load the reader with the XML file.
       reader = new XmlTextReader("elems.xml");
  
       //Parse the XML and display the text content of each of the elements.
       while (reader.Read()){
         if (reader.IsStartElement()){
           if (reader.IsEmptyElement)
              Console.WriteLine("<{0}/>", reader.Name);
           else{
               Console.Write("<{0}> ", reader.Name);
               reader.Read(); //Read the start tag.
               if (reader.IsStartElement())  //Handle nested elements.
                 Console.Write("\r\n<{0}>", reader.Name);
               Console.WriteLine(reader.ReadString());  //Read the text content of the element.
           }
         }
       } 
       
     } 

     finally 
     {
        if (reader != null)
          reader.Close();
      }
  }
  
} // End class

    
The example uses the file, elems.xml, as input.

<book>
  <title>Pride And Prejudice</title>
  <price>19.95</price>
  <misc/>
</book>

    
See also:
XmlReader.MoveToContent

Return to top


Overloaded Method: IsStartElement(
   string name
)
Inherited
See base class member description: System.Xml.XmlReader.IsStartElement

Summary
Calls XmlReader.MoveToContent and tests if the current content node is a start tag or empty element tag and if the XmlReader.Name property of the element found matches the given argument.
C# Syntax:
public virtual bool IsStartElement(
   string name
);
Parameters:

name

The string matched against the Name property of the element found.

Return Value:
true if the resulting node is an element and the Name property matches the specified string.false if a node type other than XmlNodeType.Element was found or if the element Name property does not match the specified string.
Exceptions
Exception Type Condition
XmlException Incorrect XML is encountered in the input stream.
Remarks
This method skips white space, comments, and processing instructions until the reader is positioned on a content node. The method then tests if the current node is an element.
See also:
XmlReader.MoveToContent

Return to top


Overloaded Method: IsStartElement(
   string localname,
   string ns
)
Inherited
See base class member description: System.Xml.XmlReader.IsStartElement

Summary
Calls XmlReader.MoveToContent and tests if the current content node is a start tag or empty element tag and if the XmlReader.LocalName and XmlReader.NamespaceURI properties of the element found match the given strings.
C# Syntax:
public virtual bool IsStartElement(
   string localname,
   string ns
);
Parameters:

localname

The string to match against the LocalName property of the element found.

ns

The string to match against the NamespaceURI property of the element found.

Return Value:
true if the resulting node is an element.false if a node type other than XmlNodeType.Element was found or if the LocalName and NamespaceURI properties of the element do not match the specified strings.
Exceptions
Exception Type Condition
XmlException Incorrect XML is encountered in the input stream.
Remarks
This method skips white space, comments, and processing instructions until the reader is positioned on a content node. The method then tests if the current node is an element.
See also:
XmlReader.MoveToContent

Return to top


Overridden Method: LookupNamespace(
   string prefix
)
Summary
Resolves a namespace prefix in the current element's scope.
C# Syntax:
public override string LookupNamespace(
   string prefix
);
Parameters:

prefix

The prefix whose namespace URI you want to resolve. To match the default namespace, pass an empty string. This string does not have to be atomized.

Return Value:
The namespace URI to which the prefix maps or null if no matching prefix is found.
Exceptions
Exception Type Condition
ArgumentNullException The XmlTextReader.Namespaces property is set to true and the prefix value is null.
Remarks
              <root xmlns:a="urn:456">
               <item>
               <ref href="a:b"/>
               </item>
              </root>
                 
            
In the preceding XML, if the reader is positioned on the href attribute, the prefix a is resolved by calling reader.LookupNamesapce("a") . The returned string is urn:456 .

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Overloaded Method: MoveToAttribute(
   int i
)
Summary
Moves to the attribute with the specified index.
C# Syntax:
public override void MoveToAttribute(
   int i
);
Parameters:

i

The index of the attribute.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException The i parameter is less than 0 or greater than or equal to XmlReader.AttributeCount.
Example
The following example displays all attributes on the current node.
public void DisplayAttributes(XmlReader reader)
{
  if (reader.HasAttributes)
  {
    Console.WriteLine("Attributes of <" + reader.Name + ">");
    for (int i = 0; i < reader.AttributeCount; i++)
    {
      reader.MoveToAttribute(i);
      Console.Write(" {0}={1}", reader.Name, reader.Value);
    }
    reader.MoveToElement(); //Moves the reader back to the element node.
  }
}

    

Return to top


Overloaded Method: MoveToAttribute(
   string name
)
Summary
Moves to the attribute with the specified name.
C# Syntax:
public override bool MoveToAttribute(
   string name
);
Parameters:

name

The qualified name of the attribute.

Return Value:
true if the attribute is found; otherwise, false. If false, the reader's position does not change.
Remarks
After calling MoveToAttribute, the XmlTextReader.Name, XmlTextReader.NamespaceURI, and XmlTextReader.Prefix properties will reflect the properties of that attribute.

Return to top


Overloaded Method: MoveToAttribute(
   string localName,
   string namespaceURI
)
Summary
Moves to the attribute with the specified local name and namespace URI.
C# Syntax:
public override bool MoveToAttribute(
   string localName,
   string namespaceURI
);
Parameters:

localName

The local name of the attribute.

namespaceURI

The namespace URI of the attribute.

Return Value:
true if the attribute is found; otherwise, false. If false, the reader's position does not change.
Remarks
After calling MoveToAttribute, the XmlTextReader.Name, XmlTextReader.NamespaceURI, and XmlTextReader.Prefix properties will reflect the properties of that attribute.

Return to top


Method: MoveToContent()
Inherited
See base class member description: System.Xml.XmlReader.MoveToContent

Summary
Checks whether the current node is a content (non-white space text, CDATA, Element, EndElement, EntityReference, or EndEntity) node. If the node is not a content node, the reader skips ahead to the next content node or end of file. It skips over nodes of the following type: ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace.
C# Syntax:
public virtual XmlNodeType MoveToContent();
Return Value:
The XmlReader.NodeType of the current node found by the method or XmlNodeType.None if the reader has reached the end of the input stream.
Exceptions
Exception Type Condition
XmlException Incorrect XML encountered in the input stream.
Remarks
If the current node is an attribute node, this method moves the reader back to the element that owns the attribute.
Example
This is useful when you want to write code that can skip over random XML markup without breaking. For example, suppose you have the following code:
if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "price") 
 {
    _price = reader.ReadString();
 }

    

This code can handle the following inputs without breaking:

<price>123.4</price>

and

<?xml version="1.0"><!DOCTYPE price SYSTEM "abc"><price>123.4</price>

and

<?xml version="1.0"><!DOCTYPE price SYSTEM "abc" [<!ENTTIY p "123.4">]><price>&p;</price>

and

<!-- some test comment --><?processing instruction?><price>123.4</price>

Return to top


Overridden Method: MoveToElement()
Summary
Moves to the element that contains the current attribute node.
C# Syntax:
public override bool MoveToElement();
Return Value:
true if the reader is positioned on an attribute (the reader moves to the element that owns the attribute); false if the reader is not positioned on an attribute (the position of the reader does not change).
Remarks
Use this method to return to an element after navigating through its attributes. This method moves the reader to one of the following node types: Element, DocumentType, or XmlDeclaration.
Example
The following example displays all attributes on the current node.
public void DisplayAttributes(XmlReader reader)
{
  if (reader.HasAttributes)
  {
    Console.WriteLine("Attributes of <" + reader.Name + ">");
    for (int i = 0; i < reader.AttributeCount; i++)
    {
      reader.MoveToAttribute(i);
      Console.Write(" {0}={1}", reader.Name, reader.Value);
    }
    reader.MoveToElement(); //Moves the reader back to the element node.
  }
}

    

Return to top


Overridden Method: MoveToFirstAttribute()
Summary
Moves to the first attribute.
C# Syntax:
public override bool MoveToFirstAttribute();
Return Value:
true if an attribute exists (the reader moves to the first attribute); otherwise, false (the position of the reader does not change).
Example
The following example gets the value of the first attribute of the root node.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {
       //Load the reader with the XML file.
       reader = new XmlTextReader("attrs.xml");
  
       //Read the genre attribute.
       reader.MoveToContent();
       reader.MoveToFirstAttribute();
       string genre=reader.Value;
       Console.WriteLine("The genre value: " + genre);

     } 
     finally 
     {
        if (reader != null)
          reader.Close();
      }
  }
  
} // End class

    
The example uses the file, attrs.xml, as input.

<book genre='novel' ISBN='1-861003-78' pubdate='1987'>
</book>

    

Return to top


Overridden Method: MoveToNextAttribute()
Summary
Moves to the next attribute.
C# Syntax:
public override bool MoveToNextAttribute();
Return Value:
true if there is a next attribute; false if there are no more attributes.
Remarks
If the current node is an element node, this method is equivalent to XmlTextReader.MoveToFirstAttribute. If MoveToNextAttribute returns true, the reader moves to the next attribute; otherwise, the position of the reader does not change.
Example
The following example displays all attributes on the current node.
    public void DisplayAttributes(XmlReader reader)
    {
        if (reader.HasAttributes)
        {
            Console.WriteLine("Attributes of <" + reader.Name + ">");
            while (reader.MoveToNextAttribute())
            {
                Console.WriteLine(" {0}={1}", reader.Name, reader.Value);
            }
        }
    }

    

Return to top


Overridden Method: Read()
Summary
Reads the next node from the stream.
C# Syntax:
public override bool Read();
Return Value:
true if the next node was read successfully; false if there are no more nodes to read.
Exceptions
Exception Type Condition
XmlException An error occurred while parsing the XML.
Remarks
When a reader is first created and initialized, there is no information available. You must call Read to read the first node.
Example
The following example reads an XML file and displays each node.


using System;
using System.IO;
using System.Xml;

//Reads an XML document

public class Sample
{
  private const String filename = "items.xml";

  public static void Main()
  {
     XmlTextReader reader = null;

     try
     {  
        //Load the reader with the data file and ignore all white space nodes.         
        reader = new XmlTextReader(filename);
        reader.WhitespaceHandling = WhitespaceHandling.None;

        //Parse the file and display each of the nodes.
        while (reader.Read())
        {
           switch (reader.NodeType)
           {
             case XmlNodeType.Element:
               Console.Write("<{0}>", reader.Name);
               break;
             case XmlNodeType.Text:
               Console.Write(reader.Value);
               break;
             case XmlNodeType.CDATA:
               Console.Write("<![CDATA[{0}]]>", reader.Value);
               break;
             case XmlNodeType.ProcessingInstruction:
               Console.Write("<?{0} {1}?>", reader.Name, reader.Value);
               break;
             case XmlNodeType.Comment:
               Console.Write("<!--{0}-->", reader.Value);
               break;
             case XmlNodeType.XmlDeclaration:
               Console.Write("<?xml version='1.0'?>");
               break;
             case XmlNodeType.Document:
               break;
             case XmlNodeType.DocumentType:
               Console.Write("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
               break;
             case XmlNodeType.EntityReference:
               Console.Write(reader.Name);
               break;
             case XmlNodeType.EndElement:
               Console.Write("</{0}>", reader.Name);
               break;
           }       
        }           
     }

     finally
     {
        if (reader!=null)
          reader.Close();
     }
  }

} // End class

    

The sample uses the file items.xml.


<?xml version="1.0"?>
<!-- This is a sample XML document -->
<!DOCTYPE Items [<!ENTITY number "123">]>
<Items>
  <Item>Test with an entity: &number;</Item>
  <Item>test with a child element <more/> stuff</Item>
  <Item>test with a CDATA section <![CDATA[<456>]]> def</Item>
  <Item>Test with an char entity: &#65;</Item>
  <!-- Fourteen chars in this element.-->
  <Item>1234567890ABCD</Item>
</Items>

    
See also:
EntityHandling

Return to top


Overridden Method: ReadAttributeValue()
Summary
Parses the attribute value into one or more Text, EntityReference, or EndEntity nodes.
C# Syntax:
public override bool ReadAttributeValue();
Return Value:
true if there are nodes to return.

false if the reader is not positioned on an attribute node when the initial call is made or if all the attribute values have been read.

An empty attribute, such as, misc="" , returns true with a single node with a value of String.Empty.

Remarks
Use this method after calling MoveToAttribute to read through the text or entity reference nodes that make up the attribute value. The XmlReader.Depth of the attribute value nodes is one plus the depth of the attribute node; it increments and decrements by one when you step into and out of general entity references.

General entities are returned as a single empty( XmlTextReader.Value is String.Empty) EntityReference node.

Example
The following example reads an attribute with text and entity nodes.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {
       //Create the XML fragment to be parsed.
       string xmlFrag ="<book genre='novel' misc='sale-item &h; 1987'></book>";
 
       //Create the XmlParserContext.
       XmlParserContext context;
       string subset = "<!ENTITY h 'hardcover'>";
       context = new XmlParserContext(null, null, "book", null, null, subset, "", "", XmlSpace.None);
        
       //Create the reader.
       reader = new XmlTextReader(xmlFrag, XmlNodeType.Element, context);
  
       //Read the misc attribute. The attribute is parsed
       //into multiple text and entity reference nodes.
       reader.MoveToContent();
       reader.MoveToAttribute("misc");
       while (reader.ReadAttributeValue()){
          if (reader.NodeType==XmlNodeType.EntityReference)
            Console.WriteLine("{0} {1}", reader.NodeType, reader.Name);
          else
             Console.WriteLine("{0} {1}", reader.NodeType, reader.Value);
        } 
     } 
     finally 
     {
        if (reader != null)
          reader.Close();
      }
  }
} // End class

    

Return to top


Method: ReadBase64(
   byte[] array,
   int offset,
   int len
)
Summary
Decodes Base64 and returns the decoded binary bytes.
C# Syntax:
public int ReadBase64(
   byte[] array,
   int offset,
   int len
);
Parameters:

array

The array of characters that serves as the buffer to which the text contents are written.

offset

The zero-based index into the array specifying where the method can begin to write to the buffer. The zero-based index into the array specifying where the method can begin to write to the buffer.

len

The number of bytes to write into the buffer.

Return Value:
The number of bytes written to the buffer.
Exceptions
Exception Type Condition
XmlException The Base64 sequence is not valid.
ArgumentNullException The value of array is null.
ArgumentOutOfRangeException offset < 0, or len < 0, or len > array. Length - offset.
Remarks
Like XmlTextReader.ReadChars, this method can be called successively to read large streams of embedded text. It decodes Base64 content and returns the decoded binary bytes (for example, an inline Base64 encoded GIF image) into the buffer. See RFC 1521. (You can obtain RFCs from the Request for Comments Web site at http://www.rfc-editor.org)
Example
The following example reads a file containing Base64 and BinHex data.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  private const string filename = "data.xml";

  public static void Main()
  {
     XmlTextReader reader = null;

     try
     {
        reader = new XmlTextReader(filename);
        reader.WhitespaceHandling = WhitespaceHandling.None;


        while (reader.Read())
        {
           if ("Base64" == reader.Name) break;
        }
        
        Console.WriteLine("Reading base64... ");
        int base64len = 0;
        byte[] base64 = new byte[1000];
        base64len = reader.ReadBase64(base64, 0, 50);
        for (int i=0; i < base64len; i++) Console.Write(base64[i]);
        while (0 != base64len)
        {            
           base64len = reader.ReadBase64(base64, 0, 50);            
           for (int i=0; i < base64len; i++) Console.Write(base64[i]);
        }

        reader.Read(); //reads end element

        Console.WriteLine("\r\nReading binhex....");
        int binhexlen = 0;
        byte[] binhex = new byte[1000];
        binhexlen = reader.ReadBinHex(binhex, 0, 50);
        for (int i=0; i < binhexlen; i++) Console.Write(binhex[i]);
        while (0 != binhexlen)
        {            
           binhexlen = reader.ReadBinHex(binhex, 0, 50);            
          for (int i=0; i < binhexlen; i++) Console.Write(binhex[i]);
        }
            
     }
     catch (Exception e)
     {
       Console.WriteLine ("Exception: {0}", e.ToString());
     }        

     finally 
     {
        Console.WriteLine();
        Console.WriteLine("Processing of the file {0} complete.", filename);
        if (reader != null)
          reader.Close();
     }
  }

}

    

The sample uses the file data.xml


<data>
<!-- sample data for base64 and binhex -->
<Base64>AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS
4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFi
Y2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlp
eYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrL
zM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w
==</Base64>
<BinHex>000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E
1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F4041
42434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F6061626364
65666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F8081828384858687
88898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AA
ABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCD
CECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0
F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF</BinHex>
</data>

    
See also:
XmlTextWriter.WriteBase64

Return to top


Method: ReadBinHex(
   byte[] array,
   int offset,
   int len
)
Summary
Decodes BinHex and returns the decoded binary bytes.
C# Syntax:
public int ReadBinHex(
   byte[] array,
   int offset,
   int len
);
Parameters:

array

The byte array that serves as the buffer to which the decoded binary bytes are written.

offset

The zero-based index into the array specifying where the method can begin to write to the buffer.

len

The number of bytes to write into the buffer.

Return Value:
The number of bytes written to your buffer.
Exceptions
Exception Type Condition
XmlException The BinHex sequence is not valid.
ArgumentNullException The value of array is null.
ArgumentOutOfRangeException offset < 0, or len < 0, or len > array. Length - offset.
Remarks
Like XmlTextReader.ReadChars, this method can be called successively to read large streams of embedded text. It decodes BinHex content and returns the decoded binary bytes (for example, an inline BinHex encoded GIF image) into the buffer.
Example
The following example reads a file containing Base64 and BinHex data.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  private const string filename = "data.xml";

  public static void Main()
  {
     XmlTextReader reader = null;

     try
     {
        reader = new XmlTextReader(filename);
        reader.WhitespaceHandling = WhitespaceHandling.None;


        while (reader.Read())
        {
           if ("Base64" == reader.Name) break;
        }
        
        Console.WriteLine("Reading base64... ");
        int base64len = 0;
        byte[] base64 = new byte[1000];
        base64len = reader.ReadBase64(base64, 0, 50);
        for (int i=0; i < base64len; i++) Console.Write(base64[i]);
        while (0 != base64len)
        {            
           base64len = reader.ReadBase64(base64, 0, 50);            
           for (int i=0; i < base64len; i++) Console.Write(base64[i]);
        }

        reader.Read(); //reads end element

        Console.WriteLine("\r\nReading binhex....");
        int binhexlen = 0;
        byte[] binhex = new byte[1000];
        binhexlen = reader.ReadBinHex(binhex, 0, 50);
        for (int i=0; i < binhexlen; i++) Console.Write(binhex[i]);
        while (0 != binhexlen)
        {            
           binhexlen = reader.ReadBinHex(binhex, 0, 50);            
          for (int i=0; i < binhexlen; i++) Console.Write(binhex[i]);
        }
            
     }
     catch (Exception e)
     {
       Console.WriteLine ("Exception: {0}", e.ToString());
     }        

     finally 
     {
        Console.WriteLine();
        Console.WriteLine("Processing of the file {0} complete.", filename);
        if (reader != null)
          reader.Close();
     }
  }

}

    

The sample uses the file data.xml


<data>
<!-- sample data for base64 and binhex -->
<Base64>AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS
4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFi
Y2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlp
eYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrL
zM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w
==</Base64>
<BinHex>000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E
1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F4041
42434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F6061626364
65666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F8081828384858687
88898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AA
ABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCD
CECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0
F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF</BinHex>
</data>

    

Return to top


Method: ReadChars(
   char[] buffer,
   int index,
   int count
)
Summary
Reads the text contents of an element into a character buffer. This method is designed to read large streams of embedded text by calling it successively.
C# Syntax:
public int ReadChars(
   char[] buffer,
   int index,
   int count
);
Parameters:

buffer

The array of characters that serves as the buffer to which the text contents are written.

index

The position within buffer where the method can begin writing text contents.

count

The number of characters to write into buffer.

Return Value:
The number of characters read. This can be 0 if the reader is not positioned on an element or if there is no more text content to return in the current context.
Exceptions
Exception Type Condition
ArgumentException count is greater than the space specified in the buffer (buffersize-index).
ArgumentNullException The buffer value is null.
ArgumentOutOfRangeException index < 0 or count < 0.
Remarks
This is the most efficient way to process very large streams of text embedded in an XML document. Rather than allocating large string objects, ReadChars returns text content a buffer at a time. This method is designed to work only on element nodes. Other node types cause ReadChars to return 0.

In the following XML, if the reader is positioned on the start tag, ReadChars returns test and positions the reader after the end tag.

<Item>test</Item>

ReadChars has the following functionality:

For example, using the following XML:

              <thing>
               some text
              </thing>
              <bar>
              </bar>
            

The reader is positioned on the <bar> element at the end of the while loop.

              if (XmlNodeType.Element == reader.NodeType && "thing" == reader.Name)
              {
               while( 0 != reader.ReadChars(buffer, 0, 1)
               {
               // Do something.
               // Attribute values are not available at this point. 
               }
              }
            
Example
The following example reads in XML using ReadChars.


using System;
using System.IO;
using System.Xml;

//Reads an XML document using ReadChars

public class Sample
{
  private const String filename = "items.xml";

  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {      
      //Declare variables used by ReadChars
      Char []buffer;
      int iCnt = 0;
      int charbuffersize;
     
      //Load the reader with the data file.  Ignore all whitespace.
      reader = new XmlTextReader(filename);
      reader.WhitespaceHandling = WhitespaceHandling.None;

      //Set variables used by ReadChars
      charbuffersize = 10;
      buffer = new Char[charbuffersize];

      //Parse the file.  Read the element content
      //using the ReadChars method.
      reader.MoveToContent();
      while ( (iCnt = reader.ReadChars(buffer,0,charbuffersize)) > 0 )
      {
        //Print out chars read and the buffer contents
        Console.WriteLine ("  Chars read to buffer:" + iCnt);
        Console.WriteLine ("  Buffer: [{0}]", new String(buffer,0,iCnt));
        //Clear the buffer
        Array.Clear(buffer,0,charbuffersize);
      }
       
    }
    finally
    {
      if (reader!=null)
        reader.Close();
    }
  }

} //End class

    
See also:
XmlTextReader.ReadBase64 | XmlTextReader.ReadBinHex

Return to top


Overloaded Method: ReadElementString()
Inherited
See base class member description: System.Xml.XmlReader.ReadElementString

Summary
Reads a text-only element.
C# Syntax:
public virtual string ReadElementString();
Return Value:
The text contained in the element that was read. An empty string if the element is empty ( <item></item> or <item/> ).
Exceptions
Exception Type Condition
XmlException The next content node is not a start tag; or the element found does not contain a simple text value.
Remarks
This is a helper method for reading simple text-only elements. It calls XmlReader.MoveToContent to find the next content node and then parses its value as a simple string.

Using the XML, <name>Arlene Huff</name> , ReadElementString consumes the element and returns the string Arlene Huff.

This method cannot handle any markup (child elements, comments, processing instructions, and so on) inside the name element, but it can concatenate multiple adjacent text and CDATA blocks.

Example
The following example uses ReadElementString to read the contents of the element nodes.
using System;
using System.IO;
using System.Xml;

//Reads an XML fragment

public class Sample
{
  private const String filename = "book.xml";

  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {           
      //Load the file and ignore all whitespace.
      reader = new XmlTextReader(filename);
      reader.WhitespaceHandling = WhitespaceHandling.None;

      //Moves the reader to the root element.
      reader.MoveToContent();

      //Read the title and price elements.
      Console.WriteLine("Content of the title element: {0}", reader.ReadElementString());
      Console.WriteLine("Content of the price element: {0}", reader.ReadElementString());; 
         
    }
    finally
    {
      if (reader!=null)
        reader.Close();
    }
  }
} // End class

    
The example uses the data file book.xml:

<!--sample XML fragment-->
<book genre='novel' ISBN='1-861003-78' misc='sale-item'>
  <title>The Handmaid's Tale</title>
  <price>14.95</price>
</book>

    

Return to top


Overloaded Method: ReadElementString(
   string name
)
Inherited
See base class member description: System.Xml.XmlReader.ReadElementString

Summary
Checks that the XmlReader.Name property of the element found matches the given string before reading a text-only element.
C# Syntax:
public virtual string ReadElementString(
   string name
);
Parameters:

name

The name to check.

Return Value:
The text contained in the element that was read. An empty string if the element is empty ( <item></item> or <item/> ).
Exceptions
Exception Type Condition
XmlException If the next content node is not a start tag; if the element Name does not match the given argument; or if the element found does not contain a simple text value.
Remarks
This is a helper method for reading simple text-only elements. It calls XmlReader.MoveToContent to find the next content node and then parses its value as a simple string.

Using the XML, <name>Arlene Huff</name> , ReadElementString consumes the element and returns the string Arlene Huff.

This method cannot handle any markup (child elements, comments, processing instructions, and so on) inside the name element, but it can concatenate multiple adjacent text and CDATA blocks.

Return to top


Overloaded Method: ReadElementString(
   string localname,
   string ns
)
Inherited
See base class member description: System.Xml.XmlReader.ReadElementString

Summary
Checks that the XmlReader.LocalName and XmlReader.NamespaceURI properties of the element found matches the given strings before reading a text-only element.
C# Syntax:
public virtual string ReadElementString(
   string localname,
   string ns
);
Parameters:

localname

The local name to check.

ns

The namespace URI to check.

Return Value:
The text contained in the element that was read. An empty string if the element is empty ( <item></item> or <item/> ).
Exceptions
Exception Type Condition
XmlException If the next content node is not a start tag; if the element LocalName or NamespaceURI do not match the given arguments; or if the element found does not contain a simple text value.
Remarks
This is a helper method for reading simple text-only elements. It calls XmlReader.MoveToContent to find the next content node and then parses its value as a simple string.

Using the XML, <name>Arlene Huff</name> , ReadElementString consumes the element and returns the string Arlene Huff.

This method cannot handle any markup (child elements, comments, processing instructions, and so on) inside the name element, but it can concatenate multiple adjacent text and CDATA blocks.

Return to top


Method: ReadEndElement()
Inherited
See base class member description: System.Xml.XmlReader.ReadEndElement

Summary
Checks that the current content node is an end tag and advances the reader to the next node.
C# Syntax:
public virtual void ReadEndElement();
Exceptions
Exception Type Condition
XmlException The current node is not an end tag or if incorrect XML is encountered in the input stream.
Example
The following example reads an XML document using the XmlReader.ReadStartElement and ReadEndElement methods.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {

     //Create the reader.
     XmlTextReader  reader = new XmlTextReader("book3.xml");

     //Parse the XML document.  ReadString is used to 
     //read the text content of the elements.
     reader.Read(); 
     reader.ReadStartElement("book");  
     reader.ReadStartElement("title");   
     Console.Write("The content of the title element:  ");
     Console.WriteLine(reader.ReadString());
     reader.ReadEndElement();
     reader.ReadStartElement("price");
     Console.Write("The content of the price element:  ");
     Console.WriteLine(reader.ReadString());
     reader.ReadEndElement();
     reader.ReadEndElement();

     //Close the reader.
     reader.Close();
     
  }
} // End class

    
The example uses the file, book3.xml, as input.
<book>
  <title>Pride And Prejudice</title>
  <price>19.95</price>
</book>

    
See also:
XmlReader.ReadStartElement

Return to top


Overridden Method: ReadInnerXml()
Summary
Reads all the content, including markup, as a string.
C# Syntax:
public override string ReadInnerXml();
Return Value:
All the XML content, including markup, in the current node. If the current node has no children, an empty string is returned.

If the current node is neither an element nor attribute, an empty string is returned.

Exceptions
Exception Type Condition
XmlException The XML was not well-formed, or an error occurred while parsing the XML.
Remarks
This method returns all the content of the current node including the markup. The current node (start tag) and corresponding end node (end tag) are not returned. For example, if you had the following:
              <node>
               this <child id="123"/>
              </node>
                 
            

ReadInnerXml returns this <child id="123"/>

This method handles element and attribute nodes in the following way:



Node Type Child Content Return Value Position After the Call
Element <item>text</item> text After the end tag.
Attribute <item attr1="val1" attr2="val2">text</item> val1 Remains on the attribute node attr1 .

If the reader is positioned on a leaf node, calling ReadInnerXml is equivalent to calling XmlTextReader.Read.

This method also checks for well-formed XML.

Example
The following example compares the ReadInnerXml and XmlTextReader.ReadOuterXml methods.
using System;
using System.IO;
using System.Xml;

//Reads an XML fragment

public class Sample
{
  private const String filename = "2books.xml";

  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {          
       // Load the file and ignore all white space.
       reader = new XmlTextReader(filename);
       reader.WhitespaceHandling = WhitespaceHandling.None;

       // Moves the reader to the root element.
       reader.MoveToContent();
 
       // Moves to book node.
       reader.Read(); 

       // Note that ReadInnerXml only returns the markup of the node's children
       // so the book's attributes are not returned.
       Console.WriteLine("Read the first book using ReadInnerXml...");
       Console.WriteLine(reader.ReadInnerXml());

       // ReadOuterXml returns the markup for the current node and its children
       // so the book's attributes are also returned.
       Console.WriteLine("Read the second book using ReadOuterXml...");
       Console.WriteLine(reader.ReadOuterXml());                    

    }
    finally
    {
      if (reader!=null)
        reader.Close();
    }
  }
} // End class

    
The example uses the input file 2books.xml:
[VB, C#]
<!--sample XML fragment-->
<bookstore>
  <book genre='novel' ISBN='10-861003-324'>
    <title>The Handmaid's Tale</title>
    <price>19.95</price>
  </book>
  <book genre='novel' ISBN='1-861001-57-5'>
    <title>Pride And Prejudice</title>
    <price>24.95</price>
  </book>
</bookstore>

    

Return to top


Overridden Method: ReadOuterXml()
Summary
Reads the content, including markup, representing this node and all its children.
C# Syntax:
public override string ReadOuterXml();
Return Value:
If the reader is positioned on an element or an attribute node, this method returns all the XML content, including markup, of the current node and all its children; otherwise, it returns an empty string.
Exceptions
Exception Type Condition
XmlException The XML was not well-formed, or an error occurred while parsing the XML.
Remarks
This method is similar to XmlTextReader.ReadInnerXml except it also returns the start and end tags.

This method handles element and attribute nodes in the following manner:



Node Type Child Content Return Value Position After the Call
Element <item>text</item> <item>text</item> After the end tag.
Attribute <item attr1="val1" attr2="val2">text</item> attr="val1" Remains on the attribute node attr1 .

If the reader is positioned on a leaf node, calling ReadOuterXml is equivalent to calling XmlTextReader.Read.

This method also checks for well-formed XML.

Example
The following example compares the ReadInnerXml and ReadOuterXml methods.
using System;
using System.IO;
using System.Xml;

//Reads an XML fragment

public class Sample
{
  private const String filename = "2books.xml";

  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {          
       // Load the file and ignore all white space.
       reader = new XmlTextReader(filename);
       reader.WhitespaceHandling = WhitespaceHandling.None;

       // Moves the reader to the root element.
       reader.MoveToContent();
 
       // Moves to book node.
       reader.Read(); 

       // Note that ReadInnerXml only returns the markup of the node's children
       // so the book's attributes are not returned.
       Console.WriteLine("Read the first book using ReadInnerXml...");
       Console.WriteLine(reader.ReadInnerXml());

       // ReadOuterXml returns the markup for the current node and its children
       // so the book's attributes are also returned.
       Console.WriteLine("Read the second book using ReadOuterXml...");
       Console.WriteLine(reader.ReadOuterXml());                    

    }
    finally
    {
      if (reader!=null)
        reader.Close();
    }
  }
} // End class

    
The example uses the input file 2books.xml:
[VB, C#]
<!--sample XML fragment-->
<bookstore>
  <book genre='novel' ISBN='10-861003-324'>
    <title>The Handmaid's Tale</title>
    <price>19.95</price>
  </book>
  <book genre='novel' ISBN='1-861001-57-5'>
    <title>Pride And Prejudice</title>
    <price>24.95</price>
  </book>
</bookstore>

    

Return to top


Overloaded Method: ReadStartElement()
Inherited
See base class member description: System.Xml.XmlReader.ReadStartElement

Summary
Checks that the current node is an element and advances the reader to the next node.
C# Syntax:
public virtual void ReadStartElement();
Exceptions
Exception Type Condition
XmlException XmlReader.IsStartElement returns false.
Remarks
This method calls XmlReader.IsStartElement followed by XmlReader.Read to position you on the content of that element found in the input stream.
See also:
XmlReader.ReadEndElement

Return to top


Overloaded Method: ReadStartElement(
   string name
)
Inherited
See base class member description: System.Xml.XmlReader.ReadStartElement

Summary
Checks that the current content node is an element with the given XmlReader.Name and advances the reader to the next node.
C# Syntax:
public virtual void ReadStartElement(
   string name
);
Parameters:

name

The qualified name of the element.

Exceptions
Exception Type Condition
XmlException XmlReader.IsStartElement returns false or if the XmlReader.Name of the element does not match the given name.
Remarks
A call to this method corresponds to a call to XmlReader.IsStartElement followed by a call to XmlReader.Read.
Example
The following example parses an XML document using the ReadStartElement and XmlReader.ReadEndElement methods.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {

     //Create the reader.
     XmlTextReader  reader = new XmlTextReader("book3.xml");

     //Parse the XML document.  ReadString is used to 
     //read the text content of the elements.
     reader.Read(); 
     reader.ReadStartElement("book");  
     reader.ReadStartElement("title");   
     Console.Write("The content of the title element:  ");
     Console.WriteLine(reader.ReadString());
     reader.ReadEndElement();
     reader.ReadStartElement("price");
     Console.Write("The content of the price element:  ");
     Console.WriteLine(reader.ReadString());
     reader.ReadEndElement();
     reader.ReadEndElement();

     //Close the reader.
     reader.Close();
     
  }
} // End class

    
The example uses the file, book3.xml, as input.
<book>
  <title>Pride And Prejudice</title>
  <price>19.95</price>
</book>

    
See also:
XmlReader.ReadEndElement

Return to top


Overloaded Method: ReadStartElement(
   string localname,
   string ns
)
Inherited
See base class member description: System.Xml.XmlReader.ReadStartElement

Summary
Checks that the current content node is an element with the given XmlReader.LocalName and XmlReader.NamespaceURI and advances the reader to the next node.
C# Syntax:
public virtual void ReadStartElement(
   string localname,
   string ns
);
Parameters:

localname

The local name of the element.

ns

The namespace URI of the element.

Exceptions
Exception Type Condition
XmlException XmlReader.IsStartElement returns false, or the XmlReader.LocalName and XmlReader.NamespaceURI properties of the element found do not match the given arguments.
Remarks
A call to this method corresponds to a call to XmlReader.IsStartElement followed by a call to XmlReader.Read.
See also:
XmlReader.ReadEndElement

Return to top


Overridden Method: ReadString()
Summary
Reads the contents of an element or a text node as a string.
C# Syntax:
public override string ReadString();
Return Value:
The contents of the element or text node. This can be an empty string if the reader is positioned on something other than an element or text node, or if there is no more text content to return in the current context.

Note: The text node can be either an element or an attribute text node.

Exceptions
Exception Type Condition
XmlException An error occurred while parsing the XML.
Remarks
If positioned on an element, ReadString concatenates all text, significant white space, white space, and CData section node types together and returns the concatenated data as the element content. It stops when any markup is encountered. This could occur in a mixed content model, or when an element end tag is read.

If positioned on a text node, ReadString performs the same concatenation from the text node to the element end tag. If the reader is positioned on an attribute text node, ReadString has the same functionality as if the reader were position on the element start tag. It returns all the concatenated element text nodes.

Example
The following example displays the text content of each of the elements.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {
       //Load the reader with the XML file.
       reader = new XmlTextReader("elems.xml");
  
       //Parse the XML and display the text content of each of the elements.
       while (reader.Read()){
         if (reader.IsStartElement()){
           if (reader.IsEmptyElement)
              Console.WriteLine("<{0}/>", reader.Name);
           else{
               Console.Write("<{0}> ", reader.Name);
               reader.Read(); //Read the start tag.
               if (reader.IsStartElement())  //Handle nested elements.
                 Console.Write("\r\n<{0}>", reader.Name);
               Console.WriteLine(reader.ReadString());  //Read the text content of the element.
           }
         }
       } 
       
     } 

     finally 
     {
        if (reader != null)
          reader.Close();
      }
  }
  
} // End class

    
The example uses the file, elems.xml, as input.

<book>
  <title>Pride And Prejudice</title>
  <price>19.95</price>
  <misc/>
</book>

    

Return to top


Method: ResetState()
Summary
Resets the state of the reader to ReadState.Initial.
C# Syntax:
public void ResetState();
Exceptions
Exception Type Condition
InvalidOperationException Calling ResetState if the reader was constructed using an XmlParserContext.
Remarks
This method enables you to parse multiple XML documents in a single stream. When you reach the end of an XML document, you can call ResetState to reset the state of the reader in preparation for the next XML document.

The following properties are not affected by ResetState.

Example
The following example parses two XML documents in a single stream.
using System;
using System.IO;
using System.Text;
using System.Xml;

public class Sample
{
  public static void Main(){

     Encoding enc = new UTF8Encoding();
     byte[] utf8Buffer = enc.GetBytes("<root> 12345 </root>"); 

     enc = new UnicodeEncoding();
     byte[] unicodeBuffer = enc.GetBytes("<?xml version='1.0' ?><unicode> root </unicode>");

     MemoryStream memStrm = new MemoryStream();
     memStrm.Write(unicodeBuffer, 0, unicodeBuffer.Length);
     memStrm.Write(utf8Buffer, 0, utf8Buffer.Length);
     memStrm.Position = 0;

     XmlTextReader reader = new XmlTextReader(memStrm);

     while(reader.Read()) {
        Console.WriteLine("NodeType: {0}", reader.NodeType);
        if (XmlNodeType.EndElement == reader.NodeType && "root" == reader.Name) {
          break;
        }

        if (XmlNodeType.EndElement == reader.NodeType) {
          reader.ResetState();
       }
    } 

  }
}

    
See also:
ReadState

Return to top


Overridden Method: ResolveEntity()
Summary
Resolves the entity reference for EntityReference nodes.
C# Syntax:
public override void ResolveEntity();
Exceptions
Exception Type Condition
InvalidOperationException Calling this method.
Remarks
XmlTextReader cannot resolve general entities. Calling this method will throw an exception.

Return to top


Method: Skip()
Inherited
See base class member description: System.Xml.XmlReader.Skip

Summary
Skips the children of the current node.
C# Syntax:
public virtual void Skip();
Remarks
In the following XML input if the reader is positioned on the <a> node or any of its attributes, calling Skip positions the reader to the <b> node.

If the reader is positioned on a leaf node already (such as the <x> node or the text node abc ), calling Skip is the same as calling XmlReader.Read.

              <a name="bob" age="123">
               <x/>abc<y/>
               </a>
               <b>
               ...
               </b>
            

This method checks for well-formed XML.

If the reader is an XmlValidatingReader, this method also validates the skipped content.

Example
The following example parses an XML file starting on the second book node.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {
    XmlTextReader reader = null;

    try
    {

       //Load the XmlTextReader 
       reader = new XmlTextReader("2books.xml");
       reader.WhitespaceHandling = WhitespaceHandling.None;

       //Move the reader to the second book node.
       reader.MoveToContent(); 
       reader.Read();
       reader.Skip(); //Skip the first book.
  

        //Parse the file starting with the second book node.
        while (reader.Read())
        {
           switch (reader.NodeType)
           {
             case XmlNodeType.Element:
               Console.Write("<{0}", reader.Name);
               while (reader.MoveToNextAttribute()){
                 Console.Write(" {0}='{1}'", reader.Name, reader.Value);
               }
               Console.Write(">");
               break;
             case XmlNodeType.Text:
               Console.Write(reader.Value);
               break;
             case XmlNodeType.EndElement:
               Console.Write("</{0}>", reader.Name);
               break;
           }       
         }           

     } 
     finally 
     {
        if (reader != null)
          reader.Close();
      }
  } 
} // End class

    
The example uses the file, 2books.xml, as input.

<!--sample XML fragment-->
<bookstore>
  <book genre='novel' ISBN='10-861003-324'>
    <title>The Handmaid's Tale</title>
    <price>19.95</price>
  </book>
  <book genre='novel' ISBN='1-861001-57-5'>
    <title>Pride And Prejudice</title>
    <price>24.95</price>
  </book>
</bookstore>

    

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.