Share via


XmlValidatingReader 建構函式

定義

初始化 XmlValidatingReader 類別的新執行個體。

多載

XmlValidatingReader(XmlReader)

初始化驗證從指定的 XmlReader 傳回之內容的 XmlValidatingReader 類別的新執行個體。

XmlValidatingReader(Stream, XmlNodeType, XmlParserContext)

使用指定的值,初始化 XmlValidatingReader 類別的新執行個體。

XmlValidatingReader(String, XmlNodeType, XmlParserContext)

使用指定的值,初始化 XmlValidatingReader 類別的新執行個體。

XmlValidatingReader(XmlReader)

Source:
XmlValidatingReader.cs
Source:
XmlValidatingReader.cs
Source:
XmlValidatingReader.cs

初始化驗證從指定的 XmlReader 傳回之內容的 XmlValidatingReader 類別的新執行個體。

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)

參數

reader
XmlReader

在驗證時要自其讀取的 XmlReader。 目前的實作只支援 XmlTextReader

例外狀況

指定的讀取器不是 XmlTextReader

範例

下列範例會驗證兩份檔。

#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.IO
Imports System.Xml
Imports System.Xml.Schema

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

此範例會使用下列輸入檔:

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>

備註

注意

類別 XmlValidatingReader 在 .NET Framework 2.0 中已過時。 您可以使用 類別和 Create 方法建立驗證 XmlReader 實例 XmlReaderSettings 。 如需詳細資訊,請參閱 XmlReader 參考頁面的<備註>一節。

從指定 XmlReader 傳回的所有節點也會從這個驗證讀取器傳回,因此程式中不會遺失任何資訊。 此讀取器 (可能會新增未從基礎讀取器傳回的新節點,例如預設屬性和實體參考的子系) 。 指定 XmlTextReader 上設定的任何屬性也適用于這個驗證讀取器。 例如,如果提供的讀取器已設定 WhitespaceHandling.None,則此驗證讀取器也會忽略空白字元。

當外部檔案類型定義 (DTD) 或架構需要進行驗證時, XmlResolver 屬性會將 XmlResolver 物件設定為用來解析外部資源。

另請參閱

適用於

XmlValidatingReader(Stream, XmlNodeType, XmlParserContext)

Source:
XmlValidatingReader.cs
Source:
XmlValidatingReader.cs
Source:
XmlValidatingReader.cs

使用指定的值,初始化 XmlValidatingReader 類別的新執行個體。

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)

參數

xmlFragment
Stream

包含要剖析之 XML 片段的資料流。

fragType
XmlNodeType

XML 片段的 XmlNodeType。 這可以決定 XML 片段會包含哪些內容 (請參閱下表)。

context
XmlParserContext

要剖析的 XML 片段位置所在的 XmlParserContext。 它包括要使用的 XmlNameTable、編碼方式、命名空間範圍、目前的 xml:langxml:space 範圍。

例外狀況

fragType 不是下表所列的其中一個節點型別。

備註

注意

類別 XmlValidatingReader 在 .NET Framework 2.0 中已過時。 您可以使用 類別和 Create 方法建立驗證 XmlReader 實例 XmlReaderSettings 。 如需詳細資訊,請參閱 XmlReader 參考頁面的<備註>一節。

這個建構函式會將指定的字串剖析為 XML 片段。 如果 XML 片段是元素或屬性,您可以略過格式正確 XML 檔的根層級規則。

下表列出 的有效值 fragType ,以及讀取器如何剖析每個不同節點類型。

XmlNodeType 片段可能包含
項目 例如,任何有效的專案內容 (、元素、批註、處理指示、cdata、文字和實體參考的任何組合) 。
屬性 屬性的值 (引號內的元件) 。
文件 整個 XML 檔的內容;這會強制執行檔層級規則。

讀取器會使用下列步驟來判斷資料流程的編碼方式:

  1. XmlParserContext.Encoding檢查 屬性以判斷編碼方式。

  2. Encoding如果 屬性為 null ,讀取器會在資料流程開頭檢查位元組順序標記。

  3. Encoding如果屬性為 null ,而且找不到位元組順序標記,則讀取器會假設資料流程是以 UTF-8 編碼。

如果此讀取器將使用檔案類型定義驗證, (DTD) (,即 ValidationType 設定為 ValidationType.DTD 或 ValidationType.Auto) , XmlParserContext 則建構函式中指定的 必須提供所有必要的 DocumentType 資訊。

注意

無法使用 DTD 來驗證片段。 根據定義,DTD 需要載入整個檔以進行驗證。

如果此讀取器將使用XML-Data縮減 (XDR) 或 XML 架構定義語言 (XSD) 架構來驗證,請使用 Schemas 屬性來指定 XmlSchemaCollection 包含架構 (的 , XmlParserContext 不需要提供 DocumentType 資訊) 。

另請參閱

適用於

XmlValidatingReader(String, XmlNodeType, XmlParserContext)

Source:
XmlValidatingReader.cs
Source:
XmlValidatingReader.cs
Source:
XmlValidatingReader.cs

使用指定的值,初始化 XmlValidatingReader 類別的新執行個體。

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)

參數

xmlFragment
String

包含要剖析之 XML 片段的字串。

fragType
XmlNodeType

XML 片段的 XmlNodeType。 這也可以決定 XML 片段字串將會包含哪些內容 (請參閱下表)。

context
XmlParserContext

要剖析的 XML 片段位置所在的 XmlParserContext。 它包括要使用的 NameTable、編碼方式、命名空間範圍、目前的 xml:lang 和 xml:space 範圍。

例外狀況

fragType 不是下表所列的其中一個節點型別。

範例

下列範例會讀取 XML 片段。 它會使用 XmlParserContext 及其 XmlNamespaceManager 來處理命名空間比對。

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

備註

注意

類別 XmlValidatingReader 在 .NET Framework 2.0 中已過時。 您可以使用 類別和 Create 方法建立驗證 XmlReader 實例 XmlReaderSettings 。 如需詳細資訊,請參閱 XmlReader 參考頁面的<備註>一節。

這個建構函式會將指定的字串剖析為 XML 片段。 如果 XML 片段是元素或屬性,您可以略過格式正確 XML 檔的根層級規則。 這個建構函式可以處理從 ReadInnerXml 傳回的字串。

下表列出 的有效值 fragType ,以及讀取器如何剖析每個不同節點類型。

XmlNodeType 片段可能包含
項目 例如,任何有效的專案內容 (、元素、批註、處理指示、cdata、文字和實體參考的任何組合) 。
屬性 屬性的值 (引號內的元件) 。
文件 整個 XML 檔的內容;這會強制執行檔層級規則。

如果此讀取器將使用檔案類型定義 (DTD) (來驗證, ValidationType 也就是設定為 ValidationType.DTD 或 ValidationType.Auto) , XmlParserContext 則建構函式中指定的 必須提供所有必要的 DocumentType 資訊。

注意

無法使用 DTD 來驗證片段。 根據定義,DTD 需要載入整個檔以進行驗證。

如果此讀取器將使用XML-Data縮減 (XDR) 或 XML 架構定義語言 (XSD) 架構來驗證,請使用 Schemas 屬性來指定 XmlSchemaCollection 包含架構的 , (XmlParserContext 不需要提供 DocumentType 資訊) 。

另請參閱

適用於