次の方法で共有


XML スキーマの読み取りと書き込み

スキーマ オブジェクト モデル (SOM) では、XmlTextReaderXmlTextWriterXmlSchema の各クラスを使用して、ファイルまたは他のソースから XML スキーマ定義言語 (XSD) スキーマを読み取ったり、書き込んだりできます。

次のコード例では、ファイルから XML スキーマ Example.xsd を読み込み、コンソールに出力し、そのスキーマを新しいファイル New.xsd に書き込みます。

Imports System.IO
Imports System
Imports System.Xml
Imports System.Xml.Schema
Imports System.Text

Class ReadWriteSample
   Public Shared Sub Main()
      
      Try
         
         Dim reader As New XmlTextReader("Example.xsd")
         Dim myschema As XmlSchema = XmlSchema.Read(reader, Nothing)
         myschema.Write(Console.Out)
         Dim file As New FileStream("New.xsd", FileMode.Create, FileAccess.ReadWrite)
         Dim xwriter As New XmlTextWriter(file, New UTF8Encoding())
         xwriter.Formatting = Formatting.Indented
         myschema.Write(xwriter)
      
      Catch e As Exception
         Console.WriteLine(e)
      End Try
   End Sub 
End Class 
[C#]
using System.IO; 
using System;
using System.Xml;  
using System.Xml.Schema;
using System.Text; 

class ReadWriteSample {
   
public static void Main() {
 
   try{ 

   XmlTextReader reader = new XmlTextReader ("Example.xsd");
   XmlSchema myschema = XmlSchema.Read(reader, null); 
   myschema.Write(Console.Out);
   FileStream file = new FileStream ("New.xsd", FileMode.Create, FileAccess.ReadWrite);
   XmlTextWriter xwriter = new XmlTextWriter (file, new UTF8Encoding());
   xwriter.Formatting = Formatting.Indented;
   myschema.Write (xwriter);
    
    }catch(Exception e){
       Console.WriteLine(e);
    }
  }
}

入力ファイル Example.xsd の内容についての概要を示す XML スキーマを次に示します。

<?xml version="1.0"?>
<xs:schema id="play" 
                     targetNamespace="http://tempuri.org/play.xsd" 
                     elementFormDefault="qualified" 
                     xmlns="http://tempuri.org/play.xsd"
                     xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name='myShoeSize'>
 <xs:complexType>
  <xs:simpleContent>
   <xs:extension base='xs:decimal'>
    <xs:attribute name='sizing' type='xs:string' />
   </xs:extension>
  </xs:simpleContent>
 </xs:complexType>
</xs:element>
</xs:schema>

参照

XML スキーマ オブジェクト モデル (SOM) | XmlSchema クラス