次の方法で共有


XmlSchemaCollection.Add メソッド (String, String)

指定した URL で配置されたスキーマをスキーマ コレクションに追加します。

Overloads Public Function Add( _
   ByVal ns As String, _   ByVal uri As String _) As XmlSchema
[C#]
public XmlSchema Add(stringns,stringuri);
[C++]
public: XmlSchema* Add(String* ns,String* uri);
[JScript]
public function Add(
   ns : String,uri : String) : XmlSchema;

パラメータ

  • ns
    スキーマに関連付けられた名前空間 URI。XSD スキーマの場合、通常これは targetNamespace です。
  • uri
    読み込むスキーマを指定する URL。

戻り値

スキーマ コレクションに追加される XmlSchema 。追加されるスキーマが XDR スキーマであるか、またはスキーマにコンパイル エラーがある場合は null 参照 (Visual Basic では Nothing) 。

例外

例外の種類 条件
XmlSchemaException スキーマが、有効なスキーマではありません。

解説

ns が既にコレクションの別のスキーマに関連付けられている場合、コレクションの元のスキーマは追加されるスキーマに置き換えられます。たとえば、次の C# コードでは、authors.xsd がコレクションから削除され、names.xsd が追加されます。

schemaColl.Add("urn:author", "authors.xsd");
schemaColl.Add("urn:author", "names.xsd");

ns が null 参照 (Visual Basic では Nothing) で、追加されるスキーマが XML スキーマである場合、Add メソッドは、XML スキーマで定義された targetNamespace を使用して、コレクション内のスキーマを識別します。 include 要素および import 要素を通じて、または x-schema 属性を通じて、追加するスキーマに他の名前空間が含まれている場合は、アプリケーションの信頼レベルによって、これらの名前空間の解決方法が決まります。.NET Framework Version 1.0 では、常に既定の XmlUrlResolver が使用されます。

Fully-trusted code: ユーザー資格情報を持たない既定の XmlUrlResolver が外部リソースの解決に使用されます。これらのその他の名前空間のスキーマは、検証目的でだけ読み込まれます。元のスキーマとは異なり、これらのその他のスキーマは、スキーマ コレクションに明示的には追加されません。結果として、コレクション メソッドまたはコレクション プロパティのいずれを使用しても、これにはアクセスできません。認証を要求するネットワーク リソース上にこれらの外部リソースがある場合は、引数の 1 つとして XmlResolver を受け取るオーバーロードを使用し、 XmlResolver に必要な資格情報を指定してください。

Semi-trusted code: 外部参照が解決されていません。

メモ    XmlValidatingReader.Schemas プロパティを使用して XmlSchemaCollection にアクセスする場合、 Add メソッドは XmlValidatingReader.XmlResolver プロパティで指定された XmlResolver を使用します。

使用例

[Visual Basic, C#, C++] XmlSchemaCollection に格納されているスキーマを使用して、3 つの XML ファイルを検証する例を次に示します。

 
Option Strict
Option Explicit

Imports System
Imports System.IO
Imports System.Xml
Imports System.Xml.Schema
Imports Microsoft.VisualBasic

Public Class SchemaCollectionSample
    Private doc1 As String = "booksSchema.xml"
    Private doc2 As String = "booksSchemaFail.xml"
    Private doc3 As String = "newbooks.xml"
    Private schema As String = "books.xsd"
    Private schema1 As String = "schema1.xdr"
    
    Private reader As XmlTextReader = Nothing
    Private vreader As XmlValidatingReader = Nothing
    Private m_success As Boolean = True
    
    Public Sub New()

            'Load the schema collection
            Dim xsc As 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. 
        
    End Sub 'New
    
    Public Shared Sub Main()
        Dim validation As New SchemaCollectionSample()
    End Sub 'Main
    
    Private Sub Validate(filename As String, xsc As XmlSchemaCollection)
        
            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)
            
            'Use the schemas stored in the schema collection.
            vreader.Schemas.Add(xsc)
            
            'Set the validation event handler.
            AddHandler vreader.ValidationEventHandler, AddressOf ValidationCallBack
            'Read and validate the XML data.
            While vreader.Read()
            End While
            Console.WriteLine("Validation finished. Validation {0}", IIf(m_success, "successful", "failed"))
            Console.WriteLine()

            'Close the reader.
            vreader.Close()

    End Sub 'Validate
       
    
    Private Sub ValidationCallBack(sender As Object, args As ValidationEventArgs)
        m_success = False
        
        Console.Write((ControlChars.CrLf & ControlChars.Tab & "Validation error: " & args.Message))
    End Sub 'ValidationCallBack 
End Class 'SchemaCollectionSample

[C#] 
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();

  } 


  private void ValidationCallBack (object sender, ValidationEventArgs args)
  {
     m_success = false;

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

  }  
}

[C++] 
#using <mscorlib.dll>
#using <System.Xml.dll>
using namespace System;
using namespace System::IO;
using namespace System::Xml;
using namespace System::Xml::Schema;

public __gc class SchemaCollectionSample
{
private:
   XmlTextReader* reader;
   XmlValidatingReader* vreader;
   Boolean m_success;

public:
   SchemaCollectionSample ()
   {
      reader=0;
      vreader = 0;
      m_success = true;
      //Load the schema collection.
      XmlSchemaCollection* xsc = new XmlSchemaCollection();
      String* schema = S"books.xsd";
      String* schema1 = S"schema1.xdr";
      xsc->Add(S"urn:bookstore-schema", schema);  //XSD schema
      xsc->Add(S"urn:newbooks-schema", schema1);  //XDR schema

      String* doc1 = S"booksSchema.xml";
      String* doc2 = S"booksSchemaFail.xml";
      String* doc3 = S"newbooks.xml";
      //Validate the files using schemas stored in the collection.
      Validate(doc1, xsc); //Should pass.
      Validate(doc2, xsc); //Should fail.   
      Validate(doc3, xsc); //Should fail. 

   }    

private:
   void Validate(String* filename, XmlSchemaCollection* xsc)
   {

      m_success = true;
      Console::WriteLine();
      Console::WriteLine(S"Validating XML file {0}...",filename);
      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 (this, &SchemaCollectionSample::ValidationCallBack);
      //Read and validate the XML data.
      while (vreader->Read()){}
      Console::WriteLine (S"Validation finished. Validation {0}",(m_success==true?S"successful":S"failed"));
      Console::WriteLine();

      //Close the reader.
      vreader->Close();

   } 


private:
   void ValidationCallBack (Object* /*sender*/, ValidationEventArgs* args)
   {
      m_success = false;

      Console::Write(S"\r\n\tValidation error: {0}", args->Message);

   }  
};

int main ()
{
   new SchemaCollectionSample();
}

[Visual Basic, C#, C++] サンプルでは、次の 5 つの入力ファイルを使用します。

[Visual Basic, C#, C++] 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>

[Visual Basic, C#, C++] 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>

[Visual Basic, C#, C++] 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>

[Visual Basic, C#, C++] 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>

[Visual Basic, C#, C++] 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>

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ

参照

XmlSchemaCollection クラス | XmlSchemaCollection メンバ | System.Xml.Schema 名前空間 | XmlSchemaCollection.Add オーバーロードの一覧