Condividi tramite


Lettura e scrittura di uno schema XML

Il modello SOM (Schema Object Model) può essere utilizzato per leggere e scrivere schemi del linguaggio XSD (XML Schema Definition) da file o altre fonti utilizzando le classi XmlTextReader, XmlTextWriter e XmlSchema.

Nel codice di esempio che segue viene illustrata la lettura di uno schema XML da un file, Example.xsd, e la stampa del file sulla console, quindi la scrittura dello schema in un nuovo file, 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);
    }
  }
}

Lo schema XML che segue evidenzia il contenuto del file di input, Example.xsd.

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

Vedere anche

SOM (Schema Object Model) XML | Classe XmlSchema