System.Xml.XmlReader 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 abstract class XmlReader
Remarks
XmlReader 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.

XmlReader conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations and is implemented in the following classes:



Class Description
XmlTextReader Fastest implementation of XmlReader . It checks for well-formed XML, but does not support data validation. This reader cannot expand general entities and does not support default attributes.
XmlValidatingReader Implementation of XmlReader that can validate data using DTDs or schemas. This reader can also expand general entities and supports default attributes.
XmlNodeReader Implementation of XmlReader that reads XML data from an XmlNode .

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);
        

XmlReader 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.XmlReader Member List:

Public Properties
AttributeCount Read-only

When overridden in a derived class, gets the number of attributes on the current node.
BaseURI Read-only

When overridden in a derived class, gets the base URI of the current node.
CanResolveEntity Read-only

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

When overridden in a derived class, gets the depth of the current node in the XML document.
EOF Read-only

When overridden in a derived class, gets a value indicating whether the reader is positioned at the end of the stream.
HasAttributes Read-only

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

When overridden in a derived class, gets a value indicating whether the current node can have a XmlReader.Value.
IsDefault Read-only

When overridden in a derived class, 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

When overridden in a derived class, gets a value indicating whether the current node is an empty element (for example, <MyElement/> ).
Item Read-only

Overloaded:
Item[int i] {get

When overridden in a derived class, gets the value of the attribute with the specified index.
Item Read-only

Overloaded:
Item[string name] {get

When overridden in a derived class, gets the value of the attribute with the specified XmlReader.Name.
Item Read-only

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

When overridden in a derived class, gets the value of the attribute with the specified XmlReader.LocalName and XmlReader.NamespaceURI.
LocalName Read-only

When overridden in a derived class, gets the local name of the current node.
Name Read-only

When overridden in a derived class, gets the qualified name of the current node.
NamespaceURI Read-only

When overridden in a derived class, gets the namespace URI (as defined in the W3C Namespace specification) of the node on which the reader is positioned.
NameTable Read-only

When overridden in a derived class, gets the XmlNameTable associated with this implementation.
NodeType Read-only

When overridden in a derived class, gets the type of the current node.
Prefix Read-only

When overridden in a derived class, gets the namespace prefix associated with the current node.
QuoteChar Read-only

When overridden in a derived class, gets the quotation mark character used to enclose the value of an attribute node.
ReadState Read-only

When overridden in a derived class, gets the state of the reader.
Value Read-only

When overridden in a derived class, gets the text value of the current node.
XmlLang Read-only

When overridden in a derived class, gets the current xml:lang scope.
XmlSpace Read-only

When overridden in a derived class, gets the current xml:space scope.
Public Methods
Close When overridden in a derived class, 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)

When overridden in a derived class, gets the value of the attribute with the specified index.
GetAttribute Overloaded:
GetAttribute(string name)

When overridden in a derived class, gets the value of the attribute with the specified XmlReader.Name.
GetAttribute Overloaded:
GetAttribute(string name, string namespaceURI)

When overridden in a derived class, gets the value of the attribute with the specified XmlReader.LocalName and XmlReader.NamespaceURI.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

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

Derived from System.Object, the primary base class for all objects.
IsName Gets a value indicating whether the string argument is a valid XML name.
IsNameToken Gets a value indicating whether or not the string argument is a valid XML name token.
IsStartElement Overloaded:
IsStartElement()

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

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 Overloaded:
IsStartElement(string localname, string ns)

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 When overridden in a derived class, resolves a namespace prefix in the current element's scope.
MoveToAttribute Overloaded:
MoveToAttribute(int i)

When overridden in a derived class, moves to the attribute with the specified index.
MoveToAttribute Overloaded:
MoveToAttribute(string name)

When overridden in a derived class, moves to the attribute with the specified XmlReader.Name.
MoveToAttribute Overloaded:
MoveToAttribute(string name, string ns)

When overridden in a derived class, moves to the attribute with the specified XmlReader.LocalName and XmlReader.NamespaceURI.
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 When overridden in a derived class, moves to the element that contains the current attribute node.
MoveToFirstAttribute When overridden in a derived class, moves to the first attribute.
MoveToNextAttribute When overridden in a derived class, moves to the next attribute.
Read When overridden in a derived class, reads the next node from the stream.
ReadAttributeValue When overridden in a derived class, parses the attribute value into one or more Text, EntityReference, or EndEntity nodes.
ReadElementString Overloaded:
ReadElementString()

Reads a text-only element.
ReadElementString Overloaded:
ReadElementString(string name)

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

Checks that the XmlReader.LocalName and XmlReader.NamespaceURI properties of the element found matches the given strings before reading a text-only element.
ReadEndElement Checks that the current content node is an end tag and advances the reader to the next node.
ReadInnerXml When overridden in a derived class, reads all the content, including markup, as a string.
ReadOuterXml When overridden in a derived class, reads the content, including markup, representing this node and all its children.
ReadStartElement Overloaded:
ReadStartElement()

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

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

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 When overridden in a derived class, reads the contents of an element or text node as a string.
ResolveEntity When overridden in a derived class, resolves the entity reference for EntityReference nodes.
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 Default constructor. This constructor is called by derived class constructors to initialize state in this type.
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.XmlReader Member Details

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

Return to top


Property: AttributeCount (read-only)
Summary
When overridden in a derived class, gets the number of attributes on the current node.
C# Syntax:
public abstract int AttributeCount {get;}
Remarks
This property is relevant to Element, DocumentType and XmlDeclaration nodes only. (Other node types do not have attributes.)
Example
See XmlTextReader.AttributeCount (in the XmlTextReader class) for an example using this method.

Return to top


Property: BaseURI (read-only)
Summary
When overridden in a derived class, gets the base URI of the current node.
C# Syntax:
public abstract 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.

Return to top


Property: CanResolveEntity (read-only)
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


Property: Depth (read-only)
Summary
When overridden in a derived class, gets the depth of the current node in the XML document.
C# Syntax:
public abstract int Depth {get;}
Example
See XmlTextReader.Depth (in the XmlTextReader class) for an example using this property.

Return to top


Property: EOF (read-only)
Summary
When overridden in a derived class, gets a value indicating whether the reader is positioned at the end of the stream.
C# Syntax:
public abstract bool EOF {get;}

Return to top


Property: HasAttributes (read-only)
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


Property: HasValue (read-only)
Summary
When overridden in a derived class, gets a value indicating whether the current node can have a XmlReader.Value.
C# Syntax:
public abstract 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
See XmlTextReader.HasValue (in the XmlTextReader class) for a sample using this method.

Return to top


Property: IsDefault (read-only)
Summary
When overridden in a derived class, 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 abstract bool IsDefault {get;}
Remarks
IsDefault always returns false for implementations of XmlReader that do not support schema or DTD information. This property applies only to an attribute node.
Example
See XmlValidatingReader.IsDefault (in the XmlValidatingReader class) for an example using this property.

Return to top


Property: IsEmptyElement (read-only)
Summary
When overridden in a derived class, gets a value indicating whether the current node is an empty element (for example, <MyElement/> ).
C# Syntax:
public abstract 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
See XmlTextReader.IsEmptyElement (in the XmlTextReader class for an example using this property).

Return to top


Overloaded Property: Item (read-only)
Summary
When overridden in a derived class, gets the value of the attribute with the specified index.
C# Syntax:
public abstract string this[int i] {get;}
Parameters:

i

The index of the attribute.

Remarks
This property does not move the reader.
Example
See the XmlTextReader.Item property in the XmlTextReader class for an example using this property.
See also:
XmlReader.GetAttribute

Return to top


Overloaded Property: Item (read-only)
Summary
When overridden in a derived class, gets the value of the attribute with the specified XmlReader.Name.
C# Syntax:
public abstract 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"]
See also:
XmlReader.GetAttribute

Return to top


Overloaded Property: Item (read-only)
Summary
When overridden in a derived class, gets the value of the attribute with the specified XmlReader.LocalName and XmlReader.NamespaceURI.
C# Syntax:
public abstract 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:
XmlReader.GetAttribute

Return to top


Property: LocalName (read-only)
Summary
When overridden in a derived class, gets the local name of the current node.
C# Syntax:
public abstract string LocalName {get;}
Example
See XmlTextReader.LocalName (in the XmlTextReader class) for an example using this property.

Return to top


Property: Name (read-only)
Summary
When overridden in a derived class, gets the qualified name of the current node.
C# Syntax:
public abstract string Name {get;}
Example
See XmlTextReader.Name (in the XmlTextReader class) for a sample using this method.

Return to top


Property: NamespaceURI (read-only)
Summary
When overridden in a derived class, gets the namespace URI (as defined in the W3C Namespace specification) of the node on which the reader is positioned.
C# Syntax:
public abstract string NamespaceURI {get;}
Remarks
This property is relevant to Element and Attribute nodes only.
Example
See XmlTextReader.NamespaceURI (in the XmlTextReader class) for an example using this property.

Return to top


Property: NameTable (read-only)
Summary
When overridden in a derived class, gets the XmlNameTable associated with this implementation.
C# Syntax:
public abstract 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


Property: NodeType (read-only)
Summary
When overridden in a derived class, gets the type of the current node.
C# Syntax:
public abstract XmlNodeType NodeType {get;}
Example
See XmlTextReader.NodeType (in the XmlTextReader class) for a sample using this method.

Return to top


Property: Prefix (read-only)
Summary
When overridden in a derived class, gets the namespace prefix associated with the current node.
C# Syntax:
public abstract string Prefix {get;}
Example
See XmlTextReader.Prefix (in the XmlTextReader class) for an example using this property.

Return to top


Property: QuoteChar (read-only)
Summary
When overridden in a derived class, gets the quotation mark character used to enclose the value of an attribute node.
C# Syntax:
public abstract char QuoteChar {get;}
Remarks
This property applies only to an attribute node.

Return to top


Property: ReadState (read-only)
Summary
When overridden in a derived class, gets the state of the reader.
C# Syntax:
public abstract ReadState ReadState {get;}

Return to top


Property: Value (read-only)
Summary
When overridden in a derived class, gets the text value of the current node.
C# Syntax:
public abstract string Value {get;}
Example
See XmlTextReader.Value (in the XmlTextReader class) for a sample using this method.

Return to top


Property: XmlLang (read-only)
Summary
When overridden in a derived class, gets the current xml:lang scope.
C# Syntax:
public abstract 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 XmlReader.NameTable.

Example
See XmlTextReader.XmlLang (in the XmlTextReader class) for an example using this property.

Return to top


Property: XmlSpace (read-only)
Summary
When overridden in a derived class, gets the current xml:space scope.
C# Syntax:
public abstract XmlSpace XmlSpace {get;}
Example
See XmlTextReader.XmlSpace (in the XmlTextReader class) for an example using this property.

Return to top


Method: Close()
Summary
When overridden in a derived class, changes the XmlReader.ReadState to Closed.
C# Syntax:
public abstract void Close();
Remarks
This method also releases any resources held during reading. 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:
~XmlReader();

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

Return to top


Overloaded Method: GetAttribute(
   int i
)
Summary
When overridden in a derived class, gets the value of the attribute with the specified index.
C# Syntax:
public abstract 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. This method does not move the reader.
Example
See XmlTextReader.GetAttribute (in the XmlTextReader class) for an example using this method.

Return to top


Overloaded Method: GetAttribute(
   string name
)
Summary
When overridden in a derived class, gets the value of the attribute with the specified XmlReader.Name.
C# Syntax:
public abstract 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")

Return to top


Overloaded Method: GetAttribute(
   string name,
   string namespaceURI
)
Summary
When overridden in a derived class, gets the value of the attribute with the specified XmlReader.LocalName and XmlReader.NamespaceURI.
C# Syntax:
public abstract string GetAttribute(
   string name,
   string namespaceURI
);
Parameters:

name

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 XmlReader.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: 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


Method: IsName(
   string str
)
Summary
Gets a value indicating whether the string argument is a valid XML name.
C# Syntax:
public static bool IsName(
   string str
);
Parameters:

str

The name to validate.

Return Value:
true if the name is valid; otherwise, false.
Remarks
This method uses the W3C XML 1.0 Recommendation (http://www.w3.org/TR/2000/REC-xml-20001006#NT-Name) to determine whether the name is valid.

Return to top


Method: IsNameToken(
   string str
)
Summary
Gets a value indicating whether or not the string argument is a valid XML name token.
C# Syntax:
public static bool IsNameToken(
   string str
);
Parameters:

str

The name token to validate.

Return Value:
true if it is a valid name token; otherwise false.
Remarks
This method uses the W3C XML 1.0 Recommendation (http://www.w3.org/TR/2000/REC-xml-20001006#NT-Nmtoken ) to determine whether the name token is valid.

Return to top


Overloaded Method: 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
)
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
)
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


Method: LookupNamespace(
   string prefix
)
Summary
When overridden in a derived class, resolves a namespace prefix in the current element's scope.
C# Syntax:
public abstract 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.
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
When overridden in a derived class, moves to the attribute with the specified index.
C# Syntax:
public abstract void MoveToAttribute(
   int i
);
Parameters:

i

The index of the attribute.

Example
See XmlTextReader.MoveToAttribute (in the XmlTextReader class) for an example using this method.

Return to top


Overloaded Method: MoveToAttribute(
   string name
)
Summary
When overridden in a derived class, moves to the attribute with the specified XmlReader.Name.
C# Syntax:
public abstract 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 XmlReader.Name, XmlReader.NamespaceURI, and XmlReader.Prefix properties reflect the properties of that attribute.

Return to top


Overloaded Method: MoveToAttribute(
   string name,
   string ns
)
Summary
When overridden in a derived class, moves to the attribute with the specified XmlReader.LocalName and XmlReader.NamespaceURI.
C# Syntax:
public abstract bool MoveToAttribute(
   string name,
   string ns
);
Parameters:

name

The local name of the attribute.

ns

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 XmlReader.Name, XmlReader.NamespaceURI, and XmlReader.Prefix properties reflect the properties of that attribute.

Return to top


Method: 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


Method: MoveToElement()
Summary
When overridden in a derived class, moves to the element that contains the current attribute node.
C# Syntax:
public abstract 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
See XmlTextReader.MoveToElement (in the XmlTextReader class) for an example using this method.

Return to top


Method: MoveToFirstAttribute()
Summary
When overridden in a derived class, moves to the first attribute.
C# Syntax:
public abstract 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
See XmlTextReader.MoveToFirstAttribute (in the XmlTextReader class) for an example using this method.

Return to top


Method: MoveToNextAttribute()
Summary
When overridden in a derived class, moves to the next attribute.
C# Syntax:
public abstract 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 XmlReader.MoveToFirstAttribute. If MoveToNextAttribute returns true, the reader moves to the next attribute; otherwise, the position of the reader does not change.
Example
See XmlNodeReader.MoveToNextAttribute (in the XmlNodeReader class) for an example using this method.

Return to top


Method: Read()
Summary
When overridden in a derived class, reads the next node from the stream.
C# Syntax:
public abstract 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 an XmlReader is first created and initialized, there is no information available. You must call Read to read the first node.
Example
See XmlTextReader.Read (in the XmlTextReader class) for an example using this method.

Return to top


Method: ReadAttributeValue()
Summary
When overridden in a derived class, parses the attribute value into one or more Text, EntityReference, or EndEntity nodes.
C# Syntax:
public abstract 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 XmlReader.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.

Implementations of XmlReader that cannot expand general entities return the general entities as a single empty( XmlReader.Value is String.Empty) EntityReference node.

Example
See XmlTextReader.ReadAttributeValue (in the XmlTextReader class) for an example using this method.

Return to top


Overloaded Method: 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
)
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
)
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()
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


Method: ReadInnerXml()
Summary
When overridden in a derived class, reads all the content, including markup, as a string.
C# Syntax:
public abstract 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 XmlReader.Read.

This method also checks for well-formed XML.

Example
See XmlTextReader.ReadInnerXml (in the XmlTextReader class) for an example using this method.

Return to top


Method: ReadOuterXml()
Summary
When overridden in a derived class, reads the content, including markup, representing this node and all its children.
C# Syntax:
public abstract 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 XmlReader.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 XmlReader.Read.

This method also checks for well-formed XML.

Example
See XmlTextReader.ReadOuterXml (in the XmlTextReader class) for an example using this method.

Return to top


Overloaded Method: 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
)
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
)
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


Method: ReadString()
Summary
When overridden in a derived class, reads the contents of an element or text node as a string.
C# Syntax:
public abstract 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 nodes 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
See XmlTextReader.ReadString (in the XmlTextReader class) for an example using this method.

Return to top


Method: ResolveEntity()
Summary
When overridden in a derived class, resolves the entity reference for EntityReference nodes.
C# Syntax:
public abstract void ResolveEntity();
Exceptions
Exception Type Condition
InvalidOperationException The reader is not positioned on an EntityReference node; this implementation of the reader cannot resolve entities ( XmlReader.CanResolveEntity returns false).
Remarks
If the reader is positioned on an EntityReference node (XmlNodeType.EntityReference), if XmlReader.Read is called after calling this method, the entity replacement text is parsed. When the entity replacement text is finished, an EndEntity node is returned to close the entity reference scope.

Note After calling this method, if the entity is part of an attribute value, you must call XmlReader.ReadAttributeValue to step into the entity.
Example
See XmlValidatingReader.ResolveEntity (in the XmlValidatingReader class) for a sample using this method.
See also:
EntityHandling | XmlReader.CanResolveEntity

Return to top


Method: 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.