XmlValidatingReader XmlValidatingReader XmlValidatingReader XmlValidatingReader Constructors

Definition

Overloads

XmlValidatingReader(XmlReader) XmlValidatingReader(XmlReader) XmlValidatingReader(XmlReader) XmlValidatingReader(XmlReader)

Initializes a new instance of the XmlValidatingReader class that validates the content returned from the given XmlReader.

XmlValidatingReader(Stream, XmlNodeType, XmlParserContext) XmlValidatingReader(Stream, XmlNodeType, XmlParserContext) XmlValidatingReader(Stream, XmlNodeType, XmlParserContext) XmlValidatingReader(Stream, XmlNodeType, XmlParserContext)

Initializes a new instance of the XmlValidatingReader class with the specified values.

XmlValidatingReader(String, XmlNodeType, XmlParserContext) XmlValidatingReader(String, XmlNodeType, XmlParserContext) XmlValidatingReader(String, XmlNodeType, XmlParserContext) XmlValidatingReader(String, XmlNodeType, XmlParserContext)

Initializes a new instance of the XmlValidatingReader class with the specified values.

XmlValidatingReader(XmlReader) XmlValidatingReader(XmlReader) XmlValidatingReader(XmlReader) XmlValidatingReader(XmlReader)

Initializes a new instance of the XmlValidatingReader class that validates the content returned from the given XmlReader.

public:
 XmlValidatingReader(System::Xml::XmlReader ^ reader);
public XmlValidatingReader (System.Xml.XmlReader reader);
new System.Xml.XmlValidatingReader : System.Xml.XmlReader -> System.Xml.XmlValidatingReader
Public Sub New (reader As XmlReader)

Parameters

reader
XmlReader XmlReader XmlReader XmlReader

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

Exceptions

The reader specified is not an XmlTextReader.

Examples

The following example validates two documents.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
using namespace System::Xml::Schema;
public ref class Sample
{
private:
   static 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" );
   }


private:

   // Display the validation error.
   void ValidationCallBack( Object^ /*sender*/, ValidationEventArgs^ args )
   {
      m_success = false;
      Console::WriteLine( "\r\n\tValidation error: {0}", args->Message );
   }

   void Validate( String^ filename )
   {
      m_success = true;
      Console::WriteLine( "\r\n******" );
      Console::WriteLine( "Validating XML file {0}", filename );
      XmlTextReader^ txtreader = gcnew XmlTextReader( filename );
      XmlValidatingReader^ reader = gcnew XmlValidatingReader( txtreader );
      
      // Set the validation event handler
      reader->ValidationEventHandler += gcnew ValidationEventHandler( this, &Sample::ValidationCallBack );
      
      // Read XML data
      while ( reader->Read() )
      {}

      Console::WriteLine( "Validation finished. Validation {0}", (m_success == true ? (String^)"successful!" : "failed.") );
      
      // Close the reader.
      reader->Close();
   }

};

int main()
{
   Sample^ validation = gcnew Sample;
}

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.
  private void ValidationCallBack (object sender, ValidationEventArgs args)
  {
     m_success = false;
     Console.WriteLine("\r\n\tValidation error: " + args.Message );
  }
}
Imports System
Imports System.IO
Imports System.Xml
Imports System.Xml.Schema
Imports Microsoft.VisualBasic

public class Sample

  private m_success as Boolean = true

  public sub New ()
      '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")
  end sub

  public shared sub Main ()
 
      Dim validation as Sample = new Sample()
  end sub

  private sub Validate(filename as String)

      m_success = true
      Console.WriteLine()
      Console.WriteLine("******")
      Console.WriteLine("Validating XML file " + filename.ToString())
      Dim txtreader as XmlTextReader = new XmlTextReader (filename)
      Dim reader as XmlValidatingReader = new XmlValidatingReader (txtreader)

      ' Set the validation event handler
      AddHandler reader.ValidationEventHandler, AddressOf ValidationCallBack

      ' Read XML data
      while (reader.Read())
      end while
      Console.WriteLine ("Validation finished. Validation {0}", IIf(m_success, "successful!", "failed."))

      'Close the reader.
      reader.Close()
  end sub

  'Display the validation error.
  Private sub ValidationCallBack (sender as object, args as ValidationEventArgs)

     m_success = false
     Console.WriteLine()
     Console.WriteLine("  Validation error: " + args.Message )
  end sub
end class

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>

Remarks

Note

The XmlValidatingReader class is obsolete in .NET Framework 2.0. You can create a validating XmlReader instance by using the XmlReaderSettings class and the Create method. For more information, see the Remarks section of the XmlReader reference page.

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 apply to this validating reader. For example, if the supplied reader had WhitespaceHandling.None set, this validating reader also ignores white space.

When external document type definitions (DTDs) or schemas are needed for validation, the XmlResolver property sets the XmlResolver object to use for resolving external resources.

See also

XmlValidatingReader(Stream, XmlNodeType, XmlParserContext) XmlValidatingReader(Stream, XmlNodeType, XmlParserContext) XmlValidatingReader(Stream, XmlNodeType, XmlParserContext) XmlValidatingReader(Stream, XmlNodeType, XmlParserContext)

Initializes a new instance of the XmlValidatingReader class with the specified values.

public:
 XmlValidatingReader(System::IO::Stream ^ xmlFragment, System::Xml::XmlNodeType fragType, System::Xml::XmlParserContext ^ context);
public XmlValidatingReader (System.IO.Stream xmlFragment, System.Xml.XmlNodeType fragType, System.Xml.XmlParserContext context);
new System.Xml.XmlValidatingReader : System.IO.Stream * System.Xml.XmlNodeType * System.Xml.XmlParserContext -> System.Xml.XmlValidatingReader
Public Sub New (xmlFragment As Stream, fragType As XmlNodeType, context As XmlParserContext)

Parameters

xmlFragment
Stream Stream Stream Stream

The stream containing the XML fragment to parse.

fragType
XmlNodeType XmlNodeType XmlNodeType XmlNodeType

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

context
XmlParserContext XmlParserContext XmlParserContext XmlParserContext

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

Exceptions

fragType is not one of the node types listed in the table below.

Remarks

Note

The XmlValidatingReader class is obsolete in .NET Framework 2.0. You can create a validating XmlReader instance by using the XmlReaderSettings class and the Create method. For more information, see the Remarks section of the XmlReader reference page.

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, and 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 steps 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 document type definition (DTD) (that is, 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 by using a DTD. By definition a DTD requires an entire document to be loaded for validation.

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

See also

XmlValidatingReader(String, XmlNodeType, XmlParserContext) XmlValidatingReader(String, XmlNodeType, XmlParserContext) XmlValidatingReader(String, XmlNodeType, XmlParserContext) XmlValidatingReader(String, XmlNodeType, XmlParserContext)

Initializes a new instance of the XmlValidatingReader class with the specified values.

public:
 XmlValidatingReader(System::String ^ xmlFragment, System::Xml::XmlNodeType fragType, System::Xml::XmlParserContext ^ context);
public XmlValidatingReader (string xmlFragment, System.Xml.XmlNodeType fragType, System.Xml.XmlParserContext context);
new System.Xml.XmlValidatingReader : string * System.Xml.XmlNodeType * System.Xml.XmlParserContext -> System.Xml.XmlValidatingReader
Public Sub New (xmlFragment As String, fragType As XmlNodeType, context As XmlParserContext)

Parameters

xmlFragment
String String String String

The string containing the XML fragment to parse.

fragType
XmlNodeType XmlNodeType XmlNodeType XmlNodeType

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

context
XmlParserContext XmlParserContext XmlParserContext XmlParserContext

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

Exceptions

fragType is not one of the node types listed in the table below.

Examples

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()
    {
        XmlTextReader 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 XmlTextReader(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 (string.IsNullOrEmpty(reader.Prefix))
                        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
Imports System
Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()
        Dim reader As XmlTextReader = Nothing

        Try
            'Create the XML fragment to be parsed.
            Dim xmlFrag As String = "<book> " & _
                                    "<title>Pride And Prejudice</title>" & _
                                    "<bk:genre>novel</bk:genre>" & _
                                    "</book>"

            'Create the XmlNamespaceManager that is used to
            'look up namespace information.
            Dim nt As New NameTable()
            Dim nsmgr As New XmlNamespaceManager(nt)
            nsmgr.AddNamespace("bk", "urn:sample")

            'Create the XmlParserContext.
            Dim context As New XmlParserContext(Nothing, nsmgr, Nothing, XmlSpace.None)

            'Implement the reader. 
            reader = New XmlTextReader(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() Then
                    If reader.Prefix = String.Empty Then
                        Console.WriteLine("<{0}>", reader.LocalName)
                    Else
                        Console.Write("<{0}:{1}>", reader.Prefix, reader.LocalName)
                        Console.WriteLine(" The namespace URI is " & reader.NamespaceURI)
                    End If
                End If
            End While
        Finally
            If Not (reader Is Nothing) Then
                reader.Close()
            End If
        End Try
    End Sub 'Main
End Class 'Sample 

Remarks

Note

The XmlValidatingReader class is obsolete in .NET Framework 2.0. You can create a validating XmlReader instance by using the XmlReaderSettings class and the Create method. For more information, see the Remarks section of the XmlReader reference page.

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 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, and 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 by using document type definition (DTD) (that is, 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 by using DTD. By definition DTD requires an entire document to be loaded for validation.

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

See also

Applies to