System.Xml.XmlValidatingReader Class

Assembly: System.Xml.dll
Namespace: System.Xml
Summary
Represents a reader that provides DTD, XML-Data Reduced (XDR) schema, and XML Schema definition language (XSD) schema validation.
C# Syntax:
public class XmlValidatingReader : XmlReader, IXmlLineInfo
Remarks
XmlValidatingReader implements the XmlReader class and provides support for data validation. Use the XmlValidatingReader.Schemas property to have the reader validate using schema files cached in an XmlSchemaCollection. The XmlValidatingReader.ValidationType property specifies what type of validation the reader should perform. Setting the property to ValidationType.None creates a non-validating reader.

If you do not need data validation, the ability to resolve general entities, or support for default attributes, use XmlTextReader.

To read XML data from an XmlNode, use XmlNodeReader.

See also:
System.Xml Namespace

System.Xml.XmlValidatingReader Member List:

Public Constructors
ctor #1 Overloaded:
.ctor(XmlReader reader)

Initializes a new instance of the XmlValidatingReader class that validates the content returned from the given XmlReader.
ctor #2 Overloaded:
.ctor(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context)

Initializes a new instance of the XmlValidatingReader class with the specified values.
ctor #3 Overloaded:
.ctor(string xmlFragment, XmlNodeType fragType, XmlParserContext context)

Initializes a new instance of the XmlValidatingReader 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 Read-only

Overridden:
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 attribute for the document.
EntityHandling Read-write

Gets or sets a value that specifies how the reader handles entities.
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 XmlValidatingReader.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.
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.
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.
Reader Read-only

Gets the XmlReader used to construct this XmlValidatingReader.
ReadState Read-only

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

Gets a XmlSchemaCollection to use for validation.
SchemaType Read-only

Gets a schema type object.
ValidationType Read-write

Gets a value describing what type of validation to perform.
Value Read-only

Overridden:
Gets the text value of the current node.
XmlLang Read-only

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

Sets the XmlResolver used for resolving external DTD and schema location references. The XmlResolver is also used to handle any import or include elements found in XML Schema definition language (XSD) schemas.
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.
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.
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 text node as a string.
ReadTypedValue Gets the common language runtime type for the specified XML Schema definition language (XSD) type.
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.
Public Events
ValidationEventHandler Sets an event handler for receiving information about DTD, XML-Data Reduced (XDR) schema, and XML Schema definition language (XSD) schema validation errors.
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.XmlValidatingReader Member Details

Overloaded ctor #1
Summary
Initializes a new instance of the XmlValidatingReader class that validates the content returned from the given XmlReader.
C# Syntax:
public XmlValidatingReader(
   XmlReader reader
);
Parameters:

reader

The XmlReader to read from while validating. The current implementation only supports XmlTextReader.

Exceptions
Exception Type Condition
ArgumentException The reader specified is not an XmlTextReader.
Remarks
All nodes returned from the given XmlReader are also returned from this validating reader, so there is no information loss in the process. New nodes not returned from the underlying reader may be added by this reader (for example, default attributes and the children of an entity reference). Any properties set on the given XmlTextReader also applies to this validating reader. For example, if the supplied reader had WhitespaceHandling.None set, this validating reader also ignores whitespace.

When external DTDs or schemas are needed for validation the XmlValidatingReader.XmlResolver property sets the XmlResolver object to use for resolving external resources.

Example
The following example validates two documents.
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;

public class Sample
{

  private Boolean m_success = true;

  public Sample ()
  {
      //Validate the document using an external XSD schema.  Validation should fail.
      Validate("notValidXSD.xml"); 

      //Validate the document using an inline XSD. Validation should succeed.
      Validate("inlineXSD.xml");
  }    

  public static void Main ()
  {
      Sample validation = new Sample();
  }

  private void Validate(String filename)
  {    
      m_success = true;
      Console.WriteLine("\r\n******");
      Console.WriteLine("Validating XML file " + filename.ToString());
      XmlTextReader txtreader = new XmlTextReader (filename);
      XmlValidatingReader reader = new XmlValidatingReader (txtreader);

      // Set the validation event handler
      reader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);

      // Read XML data
      while (reader.Read()){}
      Console.WriteLine ("Validation finished. Validation {0}", (m_success==true ? "successful!" : "failed."));

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

  //Display the validation error.
  public void ValidationCallBack (object sender, ValidationEventArgs args)
  {
     m_success = false;
     Console.WriteLine("\r\n\tValidation error: " + args.Message );
  }
}

    

The sample uses the following input files:

notValidXSD.xml

<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="urn:bookstore-schema books.xsd">
  <book>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
  </book>
  <book genre="novel">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
</bookstore>

    

books.xsd

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="urn:bookstore-schema"
    elementFormDefault="qualified"
    targetNamespace="urn:bookstore-schema">

 <xsd:element name="bookstore" type="bookstoreType"/>

 <xsd:complexType name="bookstoreType">
  <xsd:sequence maxOccurs="unbounded">
   <xsd:element name="book"  type="bookType"/>
  </xsd:sequence>
 </xsd:complexType>

 <xsd:complexType name="bookType">
  <xsd:sequence>
   <xsd:element name="title" type="xsd:string"/>
   <xsd:element name="author" type="authorName"/>
   <xsd:element name="price"  type="xsd:decimal"/>
  </xsd:sequence>
  <xsd:attribute name="genre" type="xsd:string"/>
 </xsd:complexType>

 <xsd:complexType name="authorName">
  <xsd:sequence>
   <xsd:element name="first-name"  type="xsd:string"/>
   <xsd:element name="last-name" type="xsd:string"/>
  </xsd:sequence>
 </xsd:complexType>

</xsd:schema>

    

inlineXSD.xml

<store-data>
<!--Inline XSD schema-->
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <xsd:element name="bookstore" type="bookstoreType"/>
 <xsd:complexType name="bookstoreType">
  <xsd:sequence maxOccurs="unbounded">
   <xsd:element name="book"  type="bookType"/>
  </xsd:sequence>
 </xsd:complexType>

 <xsd:complexType name="bookType">
  <xsd:sequence>
   <xsd:element name="title" type="xsd:string"/>
   <xsd:element name="price"  type="xsd:decimal"/>
  </xsd:sequence>
  <xsd:attribute name="genre" type="xsd:string"/>
 </xsd:complexType>
</xsd:schema>
<!-- end of schema -->

<bookstore>
  <book genre="novel">
    <title>Pride And Prejudice</title>
    <price>19.95</price>
  </book>
</bookstore>
</store-data>

    
See also:
XmlTextReader

Return to top


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

xmlFragment

The stream containing the XML fragment to parse.

fragType

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

context

The XmlParserContext in which the XML fragment 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 XML fragment 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 one of the node types listed in the table below.
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 and how the reader parses 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, text, entity references).
Attribute The value of an attribute (the part inside the quotes).
Document The contents of an entire XML document; this enforces 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.

If this reader will be validating using DTD (that is, XmlValidatingReader.ValidationType is set to ValidationType.DTD or ValidationType.Auto) the XmlParserContext specified in the constructor must supply all the necessary DocumentType information.



Note It is not possible to validate a fragment using a DTD. By definition a DTD requires an entire document to be loaded for validation.

If this reader will be validating using XML-Data Reduced (XDR) or XML Schema definition language (XSD) schemas, use the XmlValidatingReader.Schemas property to specify the XmlSchemaCollection containing the schemas (that is, the XmlParserContext does not need to supply the DocumentType information).

Return to top


Overloaded ctor #3
Summary
Initializes a new instance of the XmlValidatingReader class with the specified values.
C# Syntax:
public XmlValidatingReader(
   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 XML fragment is to be parsed. This includes the NameTable to use, encoding, namespace scope, the current xml:lang and the xml:space scope. The XmlParserContext in which the XML fragment is to be parsed. This includes the NameTable to use, encoding, namespace scope, the current xml:lang and the xml:space scope.

Exceptions
Exception Type Condition
XmlException fragType is not one of the node types listed in the table below.
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 XmlValidatingReader.ReadInnerXml.

The following table lists valid values for fragType and how the reader parses 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, text, entity references).
Attribute The value of an attribute (the part inside the quotes).
Document The contents of an entire XML document; this enforces document level rules.

If this reader will be validating using DTD (that is, XmlValidatingReader.ValidationType is set to ValidationType.DTD or ValidationType.Auto) the XmlParserContext specified in the constructor must supply all the necessary DocumentType information.



Note It is not possible to validate a fragment using DTD. By definition DTD requires an entire document to be loaded for validation.

If this reader will be validating using XML-Data Reduced (XDR) or XML Schema definition language (XSD) schemas, use the XmlValidatingReader.Schemas property to specify the XmlSchemaCollection containing the schemas (the XmlParserContext does not need to supply the DocumentType information).

Example
The following example reads an XML fragment. It uses an XmlParserContext and its XmlNamespaceManager to handle namespace matching.
using System;
using System.IO;
using System.Xml;

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

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

       //Create the XmlNamespaceManager that is used to
       //look up namespace information.
       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);

       //Implement the reader. 
       reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
  
       //Parse the XML fragment.  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);
           }
         }
       }
       

     } 

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

    

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 reads all the elements on the root node.
using System;
using System.IO;
using System.Xml;

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

    try
    {
       //Create the string to parse.
       string xmlFrag="<book genre='novel' ISBN='1-861003-78' pubdate='1987'></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 XmlValidatingReader .
       reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
  
       //Read the attributes on the root element.
       reader.MoveToContent();
       if (reader.HasAttributes){
         for (int i=0; i<reader.AttributeCount; i++){
            reader.MoveToAttribute(i);
            Console.WriteLine("{0} = {1}", reader.Name, reader.Value);
         }
         //Move the reader back to the node that owns the attribute.
         reader.MoveToElement();
       }

     } 

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

    

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 parses a file and displays the base URI of each node.
using System;
using System.IO;
using System.Xml;

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

    try
    {           
        //Create the validating reader.
        txtreader = new XmlTextReader("http://localhost/uri.xml");
        reader = new XmlValidatingReader(txtreader);
        reader.ValidationType = ValidationType.None;

        //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, uri.xml, as input. The style.xml file contains the XML text <style>hardcover</style> .

<!-- XML fragment -->
<!DOCTYPE book [<!ENTITY s SYSTEM "tmp/style.xml">]>
<book genre="novel">
  <title>Pride And Prejudice</title>
  <misc>&s;</misc>
</book>

    

Return to top


Overridden Property: CanResolveEntity (read-only)
Summary
Gets a value indicating whether this reader can parse and resolve entities.
C# Syntax:
public override bool CanResolveEntity {get;}

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.
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());

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

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

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

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

    
See also:
IXmlLineInfo

Return to top


Property: Encoding (read-only)
Summary
Gets the encoding attribute for the document.
C# Syntax:
public Encoding Encoding {get;}
Remarks
When any external reference is read (such as expanding an entity in a DTD file or reading a schema file) the encoding property is set to the encoding value of the external reference. If encoding is not specified in the external reference, and there is no byte-order mark, this defaults to UTF-8.

All the encoding standards that the underlying operating system supports are supported.

Return to top


Property: EntityHandling (read-write)
Summary
Gets or sets a value that specifies how the reader handles entities.
C# Syntax:
public EntityHandling EntityHandling {get; set;}
Exceptions
Exception Type Condition
ArgumentOutOfRangeException Invalid value was specified.
Remarks
This property can be changed on the fly and takes effect after the next XmlValidatingReader.Read call.

When EntityHandling is set to ExpandCharEntities, attribute values are only partially normalized. The reader normalizes each individual text node independently from the content of adjacent entity reference nodes.

To illustrate the difference between the entity handling modes consider the following XML:

              <!DOCTYPE doc [<!ENTITY num "123">]>
               <doc> &#65; &num; </doc>
            

When EntityHandling is set to ExpandEntities the "doc" element node contains one text node with the expanded entity text:



Depth NodeType Name Value
1 Text A 123

When EntityHandling is set to ExpandCharEntites, and XmlTextReader.WhitespaceHandling is set to Significant or All, the "doc" element expands the character entity and returns the general entity as a node:



Depth NodeType Name Value
1 Text A
1 EntityReference num
1 SignificantWhitespace
Example
The following example uses the ResolveEntity method to expand a general entity.
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: 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 XmlValidatingReader.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 whitespace between markup in a mixed content model.
Text The content of the text node.
Whitespace The whitespace between markup.
XmlDeclaration The content of the declaration.
Example
The following example reads in XML with various data types and displays each of the nodes.

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

public class Sample
{

  public static void Main()
  {

    //Create the validating reader.
    XmlTextReader txtreader = new XmlTextReader("book1.xml");
    txtreader.WhitespaceHandling = WhitespaceHandling.None;
    XmlValidatingReader reader = new XmlValidatingReader(txtreader);
    reader.ValidationType = ValidationType.None;

    //Parse the file and each node and its value.
    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);
                 
    }

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


    

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 an attribute node.
Example
The following example displays all attributes nodes on the root element.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main(){

    //Create the reader.
    XmlTextReader txtreader = new XmlTextReader("book4.xml");
    XmlValidatingReader reader = new XmlValidatingReader(txtreader);

    reader.MoveToContent();

    //Display each of the attribute nodes, including default attributes.
    while (reader.MoveToNextAttribute()){
        if (reader.IsDefault)
          Console.Write("(default attribute) ");
        Console.WriteLine("{0} = {1}", reader.Name, reader.Value);  
    }           
  
    //Close the reader.
    reader.Close();     
  
  }
} // End class

    

The example uses the following files as input.

book4.xml

<!DOCTYPE book SYSTEM 'book.dtd'>
<book ISBN = '1-861001-57-5'>
  <title>Pride And Prejudice</title>
  <price>19.95</price>
</book>

    
book.dtd
<!ELEMENT book (title,price)> 
<!ATTLIST book 
   genre CDATA "novel"
   ISBN CDATA #REQUIRED>
<!ELEMENT title (#PCDATA)>
<!ELEMENT price (#PCDATA)>

    

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 txtreader = null;
    XmlValidatingReader reader = null;

    try
    {
       //Implement the readers.
       txtreader = new XmlTextReader("elems.xml");
       reader = new XmlValidatingReader(txtreader);
  
       //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 XmlValidatingReader.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:
XmlValidatingReader.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 reads the value of the ISBN attribute.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {

    //Create the validating reader.
    XmlTextReader txtreader = new XmlTextReader("attrs.xml");
    XmlValidatingReader reader = new XmlValidatingReader(txtreader);

    //Read the ISBN attribute.
    reader.MoveToContent();
    string isbn =reader["ISBN"];
    Console.WriteLine("The ISBN value: " + isbn);

    //Close the reader.
    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:
XmlValidatingReader.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:
XmlValidatingReader.GetAttribute

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 reads an XML fragment.
using System;
using System.IO;
using System.Xml;

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

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

       //Create the XmlNamespaceManager that is used to
       //look up namespace information.
       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);

       //Implement the reader. 
       reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
  
       //Parse the XML fragment.  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);
           }
         }
       }
       

     } 

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

    

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;

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

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

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

        //Implement the validating reader over the text reader. 
        reader = new XmlValidatingReader(txtreader);
        reader.ValidationType = ValidationType.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 a 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;}

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 reads an XML fragment.
using System;
using System.IO;
using System.Xml;

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

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

       //Create the XmlNamespaceManager that is used to
       //look up namespace information.
       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);

       //Implement the reader. 
       reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
  
       //Parse the XML fragment.  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);
           }
         }
       }
       

     } 

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

    

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, or Notation.
Example
The following example reads an XML file and displays each of the nodes.
using System;
using System.IO;
using System.Xml;

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

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

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

        //Implement the validating reader over the text reader. 
        reader = new XmlValidatingReader(txtreader);
        reader.ValidationType = ValidationType.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 a char entity: &#65;</Item>
  <!-- Fourteen chars in this element.-->
  <Item>1234567890ABCD</Item>
</Items>

    

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 reads an XML fragment.
using System;
using System.IO;
using System.Xml;

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

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

       //Create the XmlNamespaceManager that is used to
       //look up namespace information.
       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);

       //Implement the reader. 
       reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
  
       //Parse the XML fragment.  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);
           }
         }
       }
       

     } 

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

    

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


Property: Reader (read-only)
Summary
Gets the XmlReader used to construct this XmlValidatingReader.
C# Syntax:
public XmlReader Reader {get;}
Remarks
This property allows the user to access properties specific to the supplied reader. It returns a typed XmlReader. The user should query for the type before casting.

Changing the state of the returned reader (for example, calling one of the read methods) can lead to unpredictable results.

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


Property: Schemas (read-only)
Summary
Gets a XmlSchemaCollection to use for validation.
C# Syntax:
public XmlSchemaCollection Schemas {get;}
Remarks
The XmlSchemaCollection holds pre-loaded XML-Data Reduced (XDR) and XML Schema definition language (XSD) schemas. This property gives the reader access to the cache of schemas and allows it to validate without having to re-load schemas every time. The reader does not add anything to the XmlSchemaCollection.

If the XmlSchemaCollection includes an XML schema (XSD) which contains include or import elements that reference other namespaces, the schemas for these other namespaces are loaded for validation purposes only. Unless these schemas were explicitly added to the schema collection, they will not be accessible using any of the collection methods or properties. For example, if the collection contains the schema file a.xsd which contains a reference to the schema file b.xsd, you must add b.xsd to the schema collection before you can access it using any of the collection methods or properties.



Note The schemas must be added to the XmlSchemaCollection before the first Read call.

For more information, refer to the conceptual topic at MSDN: validationofxmlwithxmlvalidatingreader.

Example
The following example validates three XML files using schemas stored in the XmlSchemaCollection.

 
 
 using System;
 using System.IO;
 using System.Xml;
 using System.Xml.Schema;
 
 public class SchemaCollectionSample
 {
   private const String doc1 = "booksSchema.xml";
   private const String doc2 = "booksSchemaFail.xml";
   private const String doc3 = "newbooks.xml";
   private const String schema = "books.xsd";
   private const String schema1 = "schema1.xdr";
   
   private XmlTextReader reader=null;
   private XmlValidatingReader vreader = null;
   private Boolean m_success = true;
 
   public SchemaCollectionSample ()
   {
     //Load the schema collection.
     XmlSchemaCollection xsc = new XmlSchemaCollection();
     xsc.Add("urn:bookstore-schema", schema);  //XSD schema
     xsc.Add("urn:newbooks-schema", schema1);  //XDR schema
 
     //Validate the files using schemas stored in the collection.
     Validate(doc1, xsc); //Should pass.
     Validate(doc2, xsc); //Should fail.   
     Validate(doc3, xsc); //Should fail. 
 
   }    
 
   public static void Main ()
   {
       SchemaCollectionSample validation = new SchemaCollectionSample();
   }
 
   private void Validate(String filename, XmlSchemaCollection xsc)
   {
    
      m_success = true;
      Console.WriteLine();
      Console.WriteLine("Validating XML file {0}...", filename.ToString());
      reader = new XmlTextReader (filename);
         
      //Create a validating reader.
     vreader = new XmlValidatingReader (reader);

      //Validate using the schemas stored in the schema collection.
      vreader.Schemas.Add(xsc);
  
      //Set the validation event handler
      vreader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
      //Read and validate the XML data.
      while (vreader.Read()){}
      Console.WriteLine ("Validation finished. Validation {0}", (m_success==true ? "successful" : "failed"));
      Console.WriteLine();

      //Close the reader.
      vreader.Close();
 
   } 
 
 
   public void ValidationCallBack (object sender, ValidationEventArgs args)
   {
      m_success = false;
 
      Console.Write("\r\n\tValidation error: " + args.Message);

   }  
 }

    

The sample uses the following five input files:

booksSchema.xml


<?xml version='1.0'?>
 <bookstore xmlns="urn:bookstore-schema">
   <book genre="autobiography">
     <title>The Autobiography of Benjamin Franklin</title>
     <author>
       <first-name>Benjamin</first-name>
       <last-name>Franklin</last-name>
     </author>
     <price>8.99</price>
   </book>
   <book genre="novel">
     <title>The Confidence Man</title>
     <author>
       <first-name>Herman</first-name>
       <last-name>Melville</last-name>
     </author>
     <price>11.99</price>
   </book>
 </bookstore>

    

booksSchemaFail.xml


<?xml version='1.0'?>
 <bookstore xmlns="urn:bookstore-schema">
   <book>
     <author>
       <first-name>Benjamin</first-name>
       <last-name>Franklin</last-name>
     </author>
   </book>
   <book genre="novel">
     <title>The Confidence Man</title>
     <author>
       <first-name>Herman</first-name>
       <last-name>Melville</last-name>
     </author>
     <price>11.99</price>
   </book>
   <book genre="philosophy">
     <title>The Gorgias</title>
     <author>
       <name>Plato</name>
     </author>
     <price>9.99</price>
   </book>
 </bookstore>

    

newbooks.xml


<?xml version='1.0'?>
<bookstore xmlns="urn:newbooks-schema">
  <book genre="novel" style="hardcover">
    <title>The Handmaid's Tale</title>
    <author>
      <first-name>Margaret</first-name>
      <last-name>Atwood</last-name>
    </author>
    <price>19.95</price>
  </book>
  <book genre="novel" style="other">
    <title>The Poisonwood Bible</title>
    <author>
      <first-name>Barbara</first-name>
      <last-name>Kingsolver</last-name>
    </author>
    <price>11.99</price>
  </book>
</bookstore>

    

books.xsd


<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
     xmlns="urn:bookstore-schema"
     elementFormDefault="qualified"
     targetNamespace="urn:bookstore-schema">
 
  <xsd:element name="bookstore" type="bookstoreType"/>
 
  <xsd:complexType name="bookstoreType">
   <xsd:sequence maxOccurs="unbounded">
    <xsd:element name="book"  type="bookType"/>
   </xsd:sequence>
  </xsd:complexType>
 
  <xsd:complexType name="bookType">
   <xsd:sequence>
    <xsd:element name="title" type="xsd:string"/>
    <xsd:element name="author" type="authorName"/>
    <xsd:element name="price"  type="xsd:decimal"/>
   </xsd:sequence>
   <xsd:attribute name="genre" type="xsd:string"/>
  </xsd:complexType>
 
  <xsd:complexType name="authorName">
   <xsd:sequence>
    <xsd:element name="first-name"  type="xsd:string"/>
    <xsd:element name="last-name" type="xsd:string"/>
   </xsd:sequence>
  </xsd:complexType>
 
 </xsd:schema>

    

schema1.xdr


<?xml version="1.0"?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data"
        xmlns:dt="urn:schemas-microsoft-com:datatypes">
  <ElementType name="first-name" content="textOnly"/>
  <ElementType name="last-name" content="textOnly"/>
  <ElementType name="name" content="textOnly"/>
  <ElementType name="price" content="textOnly" dt:type="fixed.14.4"/>
  <ElementType name="author" content="eltOnly" order="one">
    <group order="seq">
      <element type="name"/>
    </group>
    <group order="seq">
      <element type="first-name"/>
      <element type="last-name"/>
    </group>
  </ElementType>
  <ElementType name="title" content="textOnly"/>
  <AttributeType name="genre" dt:type="string"/>
  <AttributeType name="style" dt:type="enumeration"
        dt:values="paperback hardcover"/>
  <ElementType name="book" content="eltOnly">
    <attribute type="genre" required="yes"/>
    <attribute type="style" required="yes"/>
    <element type="title"/>
    <element type="author"/>
    <element type="price"/>
  </ElementType>
  <ElementType name="bookstore" content="eltOnly">
    <element type="book"/>
  </ElementType>
</Schema>

    

Return to top


Property: SchemaType (read-only)
Summary
Gets a schema type object.
C# Syntax:
public object SchemaType {get;}
Remarks
The user needs to test for the returned type. For example
              object obj = vreader.SchemaType;
              if (obj is XmlSchemaType)
              {
                XmlSchemaType st = (XmlSchemaType)obj;
                // use XmlSchemaType object
              }
              if (obj is XmlSchemaDatatype)
              {
                XmlSchemaDatatype sd = (XmlSchemaDatatype)obj;
                Type vt = sd.ValueType;
                // use XmlSchemaDatatype object
              }
                 
            

If XML Schema (XSD) validation is being performed then the XmlSchemaType or XmlSchemaDatatype corresponds to the current element being read. If DTD validation is being performed this property returns null.

XmlSchemaDatatype is returned if the current element, or attribute, is a simple type which can specify special validation constraints on the simple types, like min and max.

XmlSchemaSimpleType is returned if the current element, or attribute, is a user defined simpleType.

XmlSchemaComplexType is returned if the current element is a user defined complexType. This type cannot be returned by attributes.



Note If XmlValidatingReader.ValidationType has been set to ValidationType.None, no data type information is provided from either schemas or DTDs.
Example
The following example displays the type information for each of the elements in the XML document.
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;

public class Sample{

  public static void Main(){
  
  XmlTextReader tr = new XmlTextReader("booksSchema.xml");
  XmlValidatingReader vr = new XmlValidatingReader(tr);
 
  vr.Schemas.Add(null, "books.xsd");
  vr.ValidationType = ValidationType.Schema;
  vr.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
 
  while(vr.Read()){
    if(vr.NodeType == XmlNodeType.Element){
      if(vr.SchemaType is XmlSchemaComplexType){
        XmlSchemaComplexType sct = (XmlSchemaComplexType)vr.SchemaType;
        Console.WriteLine("{0}({1})", vr.Name, sct.Name);
      }
      else{
        object value = vr.ReadTypedValue();
        Console.WriteLine("{0}({1}):{2}", vr.Name, value.GetType().Name, value);
      }
    }
  }
 }

  public static void ValidationCallBack (object sender, ValidationEventArgs args){
    Console.WriteLine("***Validation error");
    Console.WriteLine("\tSeverity:{0}", args.Severity);
    Console.WriteLine("\tMessage  :{0}", args.Message);
  }
}

    

The example uses the following input files.

booksSchema.xml

<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema">
  <book genre="autobiography">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
</bookstore>

    
books.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="urn:bookstore-schema"
    elementFormDefault="qualified"
    targetNamespace="urn:bookstore-schema">

 <xsd:element name="bookstore" type="bookstoreType"/>

 <xsd:complexType name="bookstoreType">
  <xsd:sequence maxOccurs="unbounded">
   <xsd:element name="book"  type="bookType"/>
  </xsd:sequence>
 </xsd:complexType>

 <xsd:complexType name="bookType">
  <xsd:sequence>
   <xsd:element name="title" type="xsd:string"/>
   <xsd:element name="author" type="authorName"/>
   <xsd:element name="price"  type="xsd:decimal"/>
  </xsd:sequence>
  <xsd:attribute name="genre" type="xsd:string"/>
 </xsd:complexType>

 <xsd:complexType name="authorName">
  <xsd:sequence>
   <xsd:element name="first-name"  type="xsd:string"/>
   <xsd:element name="last-name" type="xsd:string"/>
  </xsd:sequence>
 </xsd:complexType>

</xsd:schema>

    

Return to top


Property: ValidationType (read-write)
Summary
Gets a value describing what type of validation to perform.
C# Syntax:
public ValidationType ValidationType {get; set;}
Exceptions
Exception Type Condition
InvalidOperationException Setting the property after a Read has been called.
Remarks
This property must be set before the first call to XmlValidatingReader.Read. Setting this property to ValidationType.None creates a non-validating reader.

If external DTDs or schemas are needed for validation, the XmlResolver is used.

For more information, refer to the conceptual topic at MSDN: validationofxmlwithxmlvalidatingreader.

Example
The following example validates two files.
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;

public class Sample
{
  private const String doc1 = "notValid.xml";
  private const String doc2 = "cdDTD.xml";
  private const String doc3 = "book1.xml";

  private XmlTextReader txtreader = null;
  private XmlValidatingReader reader = null;
  private Boolean m_success = true;

  public Sample ()
  {
      //Parse the files and validate when requested.
      Validate(doc1, ValidationType.XDR);  //Validation should fail.
      Validate(doc2, ValidationType.DTD);  //Validation should fail.
      Validate(doc3, ValidationType.None); //No validation performed.

  }    

  public static void Main ()
  {
      Sample validation = new Sample();
  }

  private void Validate(String filename, ValidationType vt)
  {
    try
    {    
        //Implement the readers.  Set the ValidationType.
        txtreader = new XmlTextReader(filename);
        reader = new XmlValidatingReader(txtreader);
        reader.ValidationType = vt;

        //If the reader is set to validate, set the event handler.
        if (vt==ValidationType.None)
           Console.WriteLine("\nParsing XML file " + filename.ToString());
        else{
           Console.WriteLine("\nValidating XML file " + filename.ToString());
           m_success = true;
           //Set the validation event handler.
           reader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
        }

        // Read XML data
        while (reader.Read()){}

        if (vt==ValidationType.None)
           Console.WriteLine("Finished parsing file.");
        else
          Console.WriteLine ("Validation finished. Validation {0}", (m_success==true ? "successful" : "failed"));
     }

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

  }
  
  //Display the validation errors.
  public void ValidationCallBack (object sender, ValidationEventArgs args)
  {
     m_success = false;

     Console.Write("\r\n\tValidation error: " + args.Message);

  }
}

    

The sample uses the following four input files:

notValid.xml (Note: The "x-schema:" prefix identifies the XDR schema for the reader.)


<?xml version='1.0'?>
<bookstore xmlns="x-schema:schema1.xdr">
  <book genre="novel" style="hardcover">
    <title>The Handmaid's Tale</title>
    <author>
      <first-name>Margaret</first-name>
      <last-name>Atwood</last-name>
    </author>
    <price>19.95</price>
  </book>
  <book genre="novel" style="other">
    <title>The Poisonwood Bible</title>
    <author>
      <first-name>Barbara</first-name>
      <last-name>Kingsolver</last-name>
    </author>
    <price>11.99</price>
  </book>
</bookstore>

    

schema1.xdr


<?xml version="1.0"?>
 <Schema xmlns="urn:schemas-microsoft-com:xml-data"
         xmlns:dt="urn:schemas-microsoft-com:datatypes">
   <ElementType name="first-name" content="textOnly"/>
   <ElementType name="last-name" content="textOnly"/>
   <ElementType name="name" content="textOnly"/>
   <ElementType name="price" content="textOnly" dt:type="fixed.14.4"/>
   <ElementType name="author" content="eltOnly" order="one">
     <group order="seq">
       <element type="name"/>
     </group>
     <group order="seq">
       <element type="first-name"/>
       <element type="last-name"/>
     </group>
   </ElementType>
   <ElementType name="title" content="textOnly"/>
   <AttributeType name="genre" dt:type="string"/>
   <AttributeType name="style" dt:type="enumeration"
         dt:values="paperback hardcover"/>
   <ElementType name="book" content="eltOnly">
     <attribute type="genre" required="yes"/>
     <attribute type="style" required="yes"/>
     <element type="title"/>
     <element type="author"/>
     <element type="price"/>
   </ElementType>
   <ElementType name="bookstore" content="eltOnly">
     <element type="book"/>
   </ElementType>
 </Schema>

    

cdDTD.xml


<!--XML file using a DTD-->
<!DOCTYPE bookstore [
  <!ELEMENT bookstore (cd)*> 
  <!ELEMENT cd (title,artist,price)>
  <!ATTLIST cd genre CDATA #REQUIRED>
  <!ELEMENT title (#PCDATA)>
  <!ELEMENT artist (#PCDATA)>
  <!ELEMENT price (#PCDATA)>]>
<bookstore>
  <cd genre="alternative"  ISBN="2-3631-4">
    <title>Americana</title>
    <artist>Offspring</artist>
    <price>16.95</price>
  </cd>
</bookstore>

    
book1.xml

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

    

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;

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

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

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

        //Implement the validating reader over the text reader. 
        reader = new XmlValidatingReader(txtreader);
        reader.ValidationType = ValidationType.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 a char entity: &#65;</Item>
  <!-- Fourteen chars in this element.-->
  <Item>1234567890ABCD</Item>
</Items>

    

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 XmlValidatingReader.NameTable.

Return to top


Property: XmlResolver (write-only)
Summary
Sets the XmlResolver used for resolving external DTD and schema location references. The XmlResolver is also used to handle any import or include elements found in XML Schema definition language (XSD) schemas.
C# Syntax:
XmlResolver XmlResolver {set;}
Remarks
The XmlResolver is used to load any DTDs, entities or schemas needed to complete the validation process.

The reader uses the XmlUrlResolver by default. However, if you have implemented a custom XmlResolver, you can specify the use of your custom XmlResolver instead.

This property can be set at any time and takes affect after the next XmlValidatingReader.Read call. If this property is set to null, the reader assumes the user is not interested in resolving external references. In this case, the reader only validates against internal resources, if the resource is present.

When validating using XML-Data Reduced (XDR) or XML Schema (XSD), you can avoid the expensive load process by providing an XmlSchemaCollection using the XmlValidatingReader.Schemas property.

Example
The following example uses the XmlResolver property to specify the credentials necessary to access the networked DTD file.
using System;
using System.IO;
using System.Xml;
using System.Net;

public class Sample 
{
  public static void Main(){

    //Create the reader.
    XmlTextReader txtreader = new XmlTextReader("book5.xml");
    XmlValidatingReader reader = new XmlValidatingReader(txtreader);
    txtreader.WhitespaceHandling = WhitespaceHandling.None;

    //Set the credentials necessary to access the DTD file stored on the network.
    XmlUrlResolver resolver = new XmlUrlResolver();
    NetworkCredential nc = new NetworkCredential("username","password","domain");
    resolver.Credentials = nc;
    reader.XmlResolver = resolver;

    //Display each of the element 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.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;
      }        
    }           
  
    //Close the reader.
    reader.Close();       
  }
} // End class

    

The example uses the following files as input.

book5.xml

<!DOCTYPE book SYSTEM 'http://myServer/DTDs/books.dtd'>
<book ISBN = '1-861001-57-5'>
  <title>Pride And Prejudice</title>
  <price>19.95</price>
  <misc>&h;</misc>
</book>

    
books.dtd
<!ELEMENT book (title,price,misc)> 
<!ATTLIST book 
   genre CDATA "novel"
   ISBN CDATA #REQUIRED>
<!ELEMENT title (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT misc (#PCDATA)>
<!ENTITY h "hardcover">
<!ENTITY p "paperback">

    

Return to top


Overridden Property: XmlSpace (read-only)
Summary
Gets the current xml:space scope.
C# Syntax:
public override XmlSpace XmlSpace {get;}

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 an XmlTextReader, this method also calls Close on the underlying reader. 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:
~XmlValidatingReader();

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 XmlValidatingReader.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()
  {

    //Create the validating reader.
    XmlTextReader txtreader = new XmlTextReader("attrs.xml");
    XmlValidatingReader reader = new XmlValidatingReader(txtreader);

    //Read the ISBN attribute.
    reader.MoveToContent();
    string isbn = reader.GetAttribute("ISBN");
    Console.WriteLine("The ISBN value: " + isbn);

    //Close the reader.
    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 XmlValidatingReader.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


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.
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 reads all the elements on the root node.
using System;
using System.IO;
using System.Xml;

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

    try
    {
       //Create the string to parse.
       string xmlFrag="<book genre='novel' ISBN='1-861003-78' pubdate='1987'></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 XmlValidatingReader .
       reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
  
       //Read the attributes on the root element.
       reader.MoveToContent();
       if (reader.HasAttributes){
         for (int i=0; i<reader.AttributeCount; i++){
            reader.MoveToAttribute(i);
            Console.WriteLine("{0} = {1}", reader.Name, reader.Value);
         }
         //Move the reader back to the node that owns the attribute.
         reader.MoveToElement();
       }

     } 

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

    

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 position of the reader does not change.
Remarks
After calling this method, the XmlValidatingReader.Name, XmlValidatingReader.NamespaceURI, and XmlValidatingReader.Prefix properties reflect the properties of that attribute.
Example
The following example reads an attribute with text and entity reference nodes.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {
    XmlValidatingReader 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 and set it to not expand general entities. 
       reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
       reader.ValidationType = ValidationType.None;
       reader.EntityHandling = EntityHandling.ExpandCharEntities;
  
       //Read the misc attribute. Because EntityHandling is set to
       //ExpandCharEntities, the attribute is parsed into multiple text
       //and entity reference nodes.
       reader.MoveToContent();
       reader.MoveToAttribute("misc");
       while (reader.ReadAttributeValue()){
          if (reader.NodeType==XmlNodeType.EntityReference)
            //To expand the entity, call ResolveEntity.
            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


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 position of the reader does not change.
Remarks
After calling this method, the XmlValidatingReader.Name, XmlValidatingReader.NamespaceURI, and XmlValidatingReader.Prefix properties 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 reads all the elements on the root node.
using System;
using System.IO;
using System.Xml;

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

    try
    {
       //Create the string to parse.
       string xmlFrag="<book genre='novel' ISBN='1-861003-78' pubdate='1987'></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 XmlValidatingReader .
       reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
  
       //Read the attributes on the root element.
       reader.MoveToContent();
       if (reader.HasAttributes){
         for (int i=0; i<reader.AttributeCount; i++){
            reader.MoveToAttribute(i);
            Console.WriteLine("{0} = {1}", reader.Name, reader.Value);
         }
         //Move the reader back to the node that owns the attribute.
         reader.MoveToElement();
       }

     } 

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

    

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 reads an XML fragment.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {

    //Create the validating reader.
    XmlTextReader txtreader = new XmlTextReader("attrs.xml");
    XmlValidatingReader reader = new XmlValidatingReader(txtreader);

    //Read the genre attribute.
    reader.MoveToFirstAttribute();
    string genre=reader.Value;
    Console.WriteLine("The genre value: " + genre);

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

  } 
} // End class

    

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 XmlValidatingReader.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 reads an XML fragment.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {

    //Create the validating reader.
    XmlTextReader txtreader = new XmlTextReader("attrs.xml");
    XmlValidatingReader reader = new XmlValidatingReader(txtreader);

    //Read the genre attribute.
    reader.MoveToFirstAttribute();
    string genre=reader.Value;
    Console.WriteLine("The genre value: " + genre);

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

  } 
} // End class

    

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

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

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

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

        //Implement the validating reader over the text reader. 
        reader = new XmlValidatingReader(txtreader);
        reader.ValidationType = ValidationType.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 a char entity: &#65;</Item>
  <!-- Fourteen chars in this element.-->
  <Item>1234567890ABCD</Item>
</Items>

    

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 XmlValidatingReader.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. The Depth increments and decrements by one when you step into and out of general entity references.

For example, suppose you have the following XML: <test name="a &b; c"/>

where the entity b is defined in the DTD as follows: <!ENTITY b "123">

If XmlValidatingReader.EntityHandling is set to ExpandCharEntities, the following C# code returns the attribute value as two text nodes and one entity reference node:

              reader.MoveToAttribute("name");
               while (reader.ReadAttributeValue())
               {
               if (reader.NodeType == XmlNodeType.Text)
               {
               // at this point reader.Text == "a " or " c"
               }
               else if (reader.NodeType == XmlNodeType.EntityReference)
               {
               // at this point reader.Name == "b"
               reader.ResolveEntity();
               while (reader.ReadAttributeValue() &&
               reader.NodeType != XmlNodeType.EndEntity)
               {
               // reader.Text == "123"
               }
               }
               }
            
Example
The following example reads an attribute with text and entity reference nodes.
using System;
using System.IO;
using System.Xml;

public class Sample 
{
  public static void Main()
  {
    XmlValidatingReader 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 and set it to not expand general entities. 
       reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
       reader.ValidationType = ValidationType.None;
       reader.EntityHandling = EntityHandling.ExpandCharEntities;
  
       //Read the misc attribute. Because EntityHandling is set to
       //ExpandCharEntities, the attribute is parsed into multiple text
       //and entity reference nodes.
       reader.MoveToContent();
       reader.MoveToAttribute("misc");
       while (reader.ReadAttributeValue()){
          if (reader.NodeType==XmlNodeType.EntityReference)
            //To expand the entity, call ResolveEntity.
            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


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.

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 XmlValidatingReader.Read.

This method also checks for well-formed XML.

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

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

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

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

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

       reader.Read(); //moves to book node

       //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("\r\nRead the second book using ReadOuterXml...");
       Console.WriteLine(reader.ReadOuterXml());            
        

    }
    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


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.
Remarks
This method is similar to XmlValidatingReader.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 XmlValidatingReader.Read.

This method checks for well-formed XML and also validates the returned content.

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

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

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

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

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

       reader.Read(); //moves to book node

       //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("\r\nRead the second book using ReadOuterXml...");
       Console.WriteLine(reader.ReadOuterXml());            
        

    }
    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


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

Remarks
If positioned on an element, ReadString concatenates all text, significant whitespace, whitespace and CData section node types together and returns the concatenated data as the element content. The reader 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.

The XmlValidatingReader.EntityHandling property determines how ReadString works as follows:



Value Description
ExpandEntities Returns expanded character and general entities. This is the default.
ExpandCharEntities Returns the text content up to but not including a general entity reference. This means a general entity causes ReadString to stop. You must call Read to step over the entity reference.
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 txtreader = null;
    XmlValidatingReader reader = null;

    try
    {
       //Implement the readers.
       txtreader = new XmlTextReader("elems.xml");
       reader = new XmlValidatingReader(txtreader);
  
       //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: ReadTypedValue()
Summary
Gets the common language runtime type for the specified XML Schema definition language (XSD) type.
C# Syntax:
public object ReadTypedValue();
Return Value:
The common language runtime type for the specified XML Schema (XSD) type.
Remarks
For example, if the type is defined as xsd:int the the runtime type int32 is returned for the object. This can be tested using the Object.GetType method and cast accordingly. This property always return a subclassed type of object. An object of the type object is never returned. If the reader is positioned on an attribute, this method returns the runtime typed object, but does not change the position of the reader. If the reader is positioned on an element, ReadTypedValue reads any CDATA, text, whitespace, significant whitespace, and comment nodes, returns the runtime typed object and positions the reader on the end tag. Any types that do not have a direct mapping, for example NMTOKENS, are returned as strings.

Note If XmlValidatingReader.ValidationType has been set to ValidationType.None, data type information is not provided from either schemas or DTDs.
Example
The following example displays the type information for each of the elements in the XML document.
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;

public class Sample{

  public static void Main(){
  
  XmlTextReader tr = new XmlTextReader("booksSchema.xml");
  XmlValidatingReader vr = new XmlValidatingReader(tr);
 
  vr.Schemas.Add(null, "books.xsd");
  vr.ValidationType = ValidationType.Schema;
  vr.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
 
  while(vr.Read()){
    if(vr.NodeType == XmlNodeType.Element){
      if(vr.SchemaType is XmlSchemaComplexType){
        XmlSchemaComplexType sct = (XmlSchemaComplexType)vr.SchemaType;
        Console.WriteLine("{0}({1})", vr.Name, sct.Name);
      }
      else{
        object value = vr.ReadTypedValue();
        Console.WriteLine("{0}({1}):{2}", vr.Name, value.GetType().Name, value);
      }
    }
  }
 }

  public static void ValidationCallBack (object sender, ValidationEventArgs args){
    Console.WriteLine("***Validation error");
    Console.WriteLine("\tSeverity:{0}", args.Severity);
    Console.WriteLine("\tMessage  :{0}", args.Message);
  }
}

    

The example uses the following input files.

booksSchema.xml

<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema">
  <book genre="autobiography">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
</bookstore>

    
books.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="urn:bookstore-schema"
    elementFormDefault="qualified"
    targetNamespace="urn:bookstore-schema">

 <xsd:element name="bookstore" type="bookstoreType"/>

 <xsd:complexType name="bookstoreType">
  <xsd:sequence maxOccurs="unbounded">
   <xsd:element name="book"  type="bookType"/>
  </xsd:sequence>
 </xsd:complexType>

 <xsd:complexType name="bookType">
  <xsd:sequence>
   <xsd:element name="title" type="xsd:string"/>
   <xsd:element name="author" type="authorName"/>
   <xsd:element name="price"  type="xsd:decimal"/>
  </xsd:sequence>
  <xsd:attribute name="genre" type="xsd:string"/>
 </xsd:complexType>

 <xsd:complexType name="authorName">
  <xsd:sequence>
   <xsd:element name="first-name"  type="xsd:string"/>
   <xsd:element name="last-name" type="xsd:string"/>
  </xsd:sequence>
 </xsd:complexType>

</xsd:schema>

    

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 The reader is not positioned on an EntityReference node.
Remarks
If the reader is positioned on an EntityReference node (XmlNodeType.EntityReference), if XmlValidatingReader.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 XmlValidatingReader.ReadAttributeValue to step into the entity.
Example
The following example uses ResolveEntity to expand a general entity.
using System;
using System.IO;
using System.Xml;

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

     try
     {
       //Create and load the XmlTextReader with the XML file. 
       txtreader = new XmlTextReader("book1.xml");
       txtreader.WhitespaceHandling = WhitespaceHandling.None;

       //Create the XmlValidatingReader over the XmlTextReader.
       //Set the reader to not expand general entities.
       reader = new XmlValidatingReader(txtreader);
       reader.ValidationType = ValidationType.None;
       reader.EntityHandling = EntityHandling.ExpandCharEntities;

       reader.MoveToContent();  //Move to the root element.
       reader.Read();  //Move to title start tag.
       reader.Skip();  //Skip the title element.
      
       //Read the misc start tag.  The reader is now positioned on
       //the entity reference node.
       reader.ReadStartElement(); 

       //Because EntityHandling is set to ExpandCharEntities, you must call 
       //ResolveEntity to expand the entity.  The entity replacement text is 
       //then parsed and returned as a child node.  
       
       Console.WriteLine("Expand the entity...");
       reader.ResolveEntity();  

       Console.WriteLine("The entity replacement text is returned as a text node.");
       reader.Read();  
       Console.WriteLine("NodeType: {0} Value: {1}", reader.NodeType ,reader.Value);

       Console.WriteLine("An EndEntity node closes the entity reference scope.");
       reader.Read();
       Console.WriteLine("NodeType: {0} Name: {1}", reader.NodeType,reader.Name);
     
    }
    finally
    {
       if (reader != null)
         reader.Close();
    }
  }
}

    
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>

    
See also:
EntityHandling

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


Event: ValidationEventHandler
Summary
Sets an event handler for receiving information about DTD, XML-Data Reduced (XDR) schema, and XML Schema definition language (XSD) schema validation errors.
C# Syntax:
public event ValidationEventHandler ValidationEventHandler;
Remarks
These events occur during XmlValidatingReader.Read and only if a XmlValidatingReader.ValidationType of DTD, XDR, Schema, or Auto is specified.

If no event handler is provided an XmlException is thrown on the first validation error (Severity is equal to XmlSeverityType.Error).



Note If an element reports a validation error, the rest of the content model for that element is not validated, however, its children are validated. The reader only reports the first error for a given element.

The callback handler can use the ValidationEventArgs.Severity property to guarantee that an XML instance document is validated against a schema. The Severity property allows you to distinguish between validation errors (Severity is equal to XmlSeverityType.Error) thatindicates a fatal error, and validation warnings (Severity is equal to XmlSeverityType.Warning) that indicates that no schema information is available.

Example
The following example validates a file against an XML Schema (XSD).
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;

public class Sample
{

  private XmlTextReader txtreader = null;
  private XmlValidatingReader reader = null;
  private Boolean m_success = true;

  public Sample ()
  {
        //Validate file against the XSD schema. 
        //The validation should fail.
        Validate("notValidXSD.xml"); 
  }    

  public static void Main ()
  {
      Sample validation = new Sample();
  }

  private void Validate(String filename)
  {    
     try
     {
        Console.WriteLine("Validating XML file " + filename.ToString());
        txtreader = new XmlTextReader (filename);
        reader = new XmlValidatingReader (txtreader);

        // Set the validation event handler
        reader.ValidationEventHandler += new ValidationEventHandler (this.ValidationEventHandle);

        // Read XML data
        while (reader.Read()){}
        Console.WriteLine ("Validation finished. Validation {0}", (m_success==true ? "successful" : "failed"));
     }

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

  //Display the validation error.
  public void ValidationEventHandle (object sender, ValidationEventArgs args)
  {
     m_success = false;
     Console.WriteLine("\r\n\tValidation error: " + args.Message );
  }
}

    

The sample uses the following two input files:

notValidXSD.xml (The xsi:schemaLocation attribute identifies the XML Schema (XSD) for the reader.)


<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="urn:bookstore-schema books.xsd">
  <book>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
  </book>
  <book genre="novel">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
</bookstore>

    

books.xsd


<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="urn:bookstore-schema"
    elementFormDefault="qualified"
    targetNamespace="urn:bookstore-schema">

 <xsd:element name="bookstore" type="bookstoreType"/>

 <xsd:complexType name="bookstoreType">
  <xsd:sequence maxOccurs="unbounded">
   <xsd:element name="book"  type="bookType"/>
  </xsd:sequence>
 </xsd:complexType>

 <xsd:complexType name="bookType">
  <xsd:sequence>
   <xsd:element name="title" type="xsd:string"/>
   <xsd:element name="author" type="authorName"/>
   <xsd:element name="price"  type="xsd:decimal"/>
  </xsd:sequence>
  <xsd:attribute name="genre" type="xsd:string"/>
 </xsd:complexType>

 <xsd:complexType name="authorName">
  <xsd:sequence>
   <xsd:element name="first-name"  type="xsd:string"/>
   <xsd:element name="last-name" type="xsd:string"/>
  </xsd:sequence>
 </xsd:complexType>

</xsd:schema>

    
See also:
XmlSeverityType

Return to top


Top of page

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