Compartir a través de


Leer y escribir esquemas XML

El Modelo de objetos de esquemas (SOM, Schema Object Model) se puede utilizar para leer y escribir esquemas en lenguaje XSD (XML Schema Definition, definición de esquemas XML) en archivos o en otros orígenes mediante las clases XmlTextReader, XmlTextWriter y XmlSchema.

En el ejemplo de código siguiente se ilustra cómo se lee un esquema XML en un archivo, Example.xsd, y cómo se imprime el archivo en la consola; finalmente, el esquema se escribe en un nuevo archivo, 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);
    }
  }
}

En el siguiente esquema XML se describe el contenido del archivo de entrada, 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>

Vea también

Modelo de objetos de esquemas XML (SOM) | XmlSchema (Clase)