Bagikan melalui


Mengedit skema XML

Mengedit skema XML adalah salah satu fitur terpenting dari Schema Object Model (SOM). Semua properti pra-kompilasi skema SOM dapat digunakan untuk mengubah nilai yang ada dalam skema XML. Skema XML kemudian dapat dikompresi ulang untuk mencerminkan perubahan.

Langkah pertama dalam mengedit skema yang dimuat ke dalam SOM adalah melintasi skema. Anda harus terbiasa melintas skema menggunakan SOM API sebelum Mencoba mengedit skema. Anda juga harus terbiasa dengan properti pra-dan pasca-kompilasi pasca-Skema-Compilation-Infoset (PSCI).

Mengedit Skema XML dalam Lingkungan Digital

Di bagian ini, dua contoh kode disediakan, yang keduanya mengedit skema pelanggan yang dibuat dalam topik Membangun Skema XML . Contoh kode pertama menambahkan elemen baru PhoneNumber ke Customer elemen dan contoh kode kedua menambahkan atribut baru Title ke FirstName elemen . Sampel pertama juga memanfaatkan koleksi XmlSchema.Elements pasca-kompilasi skema sebagai cara untuk menjelajahi skema pelanggan, sedangkan contoh kode kedua menggunakan koleksi XmlSchema.Items pra-kompilasi skema.

Contoh Elemen Nomor Telepon

Contoh kode pertama ini menambahkan elemen baru PhoneNumber ke Customer elemen skema pelanggan. Contoh kode mengedit skema pelanggan dalam langkah-langkah berikut.

  1. Menambahkan skema pelanggan ke objek baru XmlSchemaSet lalu mengkompilasinya. Setiap peringatan validasi skema dan kesalahan yang ditemui saat membaca atau mengkompilasi skema ditangani oleh ValidationEventHandler delegasi.

  2. Mengambil objek yang dikompilasi XmlSchema dari XmlSchemaSet dengan melakukan iterasi melalui properti Schemas. Karena skema dikompilasi, properti Post-Schema-Compilation-Infoset (PSCI) dapat diakses.

  3. Membuat elemen PhoneNumber menggunakan kelas XmlSchemaElement, pembatasan jenis sederhana xs:string menggunakan kelas XmlSchemaSimpleType dan XmlSchemaSimpleTypeRestriction, menambahkan faset pola ke properti Facets dari pembatasan, dan menambahkan pembatasan ke properti Content dari jenis sederhana dan jenis sederhana ke SchemaType dari elemen PhoneNumber.

  4. Mengiterasi setiap XmlSchemaElement dalam koleksi Values pasca-kompilasi skema XmlSchema.Elements.

  5. QualifiedName Jika elemen adalah "Customer", mendapatkan tipe kompleks dari elemen Customer menggunakan kelas XmlSchemaComplexType dan partikel urutan dari tipe kompleks menggunakan kelas XmlSchemaSequence.

  6. Menambahkan elemen baru PhoneNumber ke urutan yang berisi elemen FirstName dan LastName yang ada menggunakan koleksi Items pra-skema-kompilasi dari urutan.

  7. Terakhir, proses ulang dan kompilasi objek yang dimodifikasi XmlSchema menggunakan metode Reprocess dan Compile dari kelas XmlSchemaSet lalu menulisnya ke konsol.

Berikut ini adalah contoh kode lengkap.

using System;
using System.Xml;
using System.Xml.Schema;

class XmlSchemaEditExample
{
    static void Main(string[] args)
    {
        // Add the customer schema to a new XmlSchemaSet and compile it.
        // Any schema validation warnings and errors encountered reading or
        // compiling the schema are handled by the ValidationEventHandler delegate.
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
        schemaSet.Add("http://www.tempuri.org", "customer.xsd");
        schemaSet.Compile();

        // Retrieve the compiled XmlSchema object from the XmlSchemaSet
        // by iterating over the Schemas property.
        XmlSchema customerSchema = null;
        foreach (XmlSchema schema in schemaSet.Schemas())
        {
            customerSchema = schema;
        }

        // Create the PhoneNumber element.
        XmlSchemaElement phoneElement = new XmlSchemaElement();
        phoneElement.Name = "PhoneNumber";

        // Create the xs:string simple type restriction.
        XmlSchemaSimpleType phoneType = new XmlSchemaSimpleType();
        XmlSchemaSimpleTypeRestriction restriction =
            new XmlSchemaSimpleTypeRestriction();
        restriction.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

        // Add a pattern facet to the restriction.
        XmlSchemaPatternFacet phonePattern = new XmlSchemaPatternFacet();
        phonePattern.Value = "\\d{3}-\\d{3}-\\d(4)";
        restriction.Facets.Add(phonePattern);

        // Add the restriction to the Content property of the simple type
        // and the simple type to the SchemaType of the PhoneNumber element.
        phoneType.Content = restriction;
        phoneElement.SchemaType = phoneType;

        // Iterate over each XmlSchemaElement in the Values collection
        // of the Elements property.
        foreach (XmlSchemaElement element in customerSchema.Elements.Values)
        {
            // If the qualified name of the element is "Customer",
            // get the complex type of the Customer element
            // and the sequence particle of the complex type.
            if (element.QualifiedName.Name.Equals("Customer"))
            {
                XmlSchemaComplexType customerType =
                    element.ElementSchemaType as XmlSchemaComplexType;
                XmlSchemaSequence sequence =
                    customerType.Particle as XmlSchemaSequence;

                // Add the new PhoneNumber element to the sequence.
                sequence.Items.Add(phoneElement);
            }
        }

        // Reprocess and compile the modified XmlSchema object and write it to the console.
        schemaSet.Reprocess(customerSchema);
        schemaSet.Compile();
        customerSchema.Write(Console.Out);
    }

    static void ValidationCallback(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.Write("WARNING: ");
        else if (args.Severity == XmlSeverityType.Error)
            Console.Write("ERROR: ");

        Console.WriteLine(args.Message);
    }
}
Imports System.Xml
Imports System.Xml.Schema

Class XmlSchemaEditExample

    Shared Sub Main()

        ' Add the customer schema to a new XmlSchemaSet and compile it.
        ' Any schema validation warnings and errors encountered reading or 
        ' compiling the schema are handled by the ValidationEventHandler delegate.
        Dim schemaSet As XmlSchemaSet = New XmlSchemaSet()
        AddHandler schemaSet.ValidationEventHandler, AddressOf ValidationCallback
        schemaSet.Add("http://www.tempuri.org", "customer.xsd")
        schemaSet.Compile()

        ' Retrieve the compiled XmlSchema object from the XmlSchemaSet
        ' by iterating over the Schemas property.
        Dim customerSchema As XmlSchema = Nothing
        For Each schema As XmlSchema In schemaSet.Schemas()
            customerSchema = schema
        Next

        ' Create the PhoneNumber element.
        Dim phoneElement As XmlSchemaElement = New XmlSchemaElement()
        phoneElement.Name = "PhoneNumber"

        ' Create the xs:string simple type restriction.
        Dim phoneType As XmlSchemaSimpleType = New XmlSchemaSimpleType()
        Dim restriction As XmlSchemaSimpleTypeRestriction = _
            New XmlSchemaSimpleTypeRestriction()
        restriction.BaseTypeName = New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")

        ' Add a pattern facet to the restriction.
        Dim phonePattern As XmlSchemaPatternFacet = New XmlSchemaPatternFacet()
        phonePattern.Value = "\\d{3}-\\d{3}-\\d(4)"
        restriction.Facets.Add(phonePattern)

        ' Add the restriction to the Content property of the simple type
        ' and the simple type to the SchemaType of the PhoneNumber element.
        phoneType.Content = restriction
        phoneElement.SchemaType = phoneType

        ' Iterate over each XmlSchemaElement in the Values collection
        ' of the Elements property.
        For Each element As XmlSchemaElement In customerSchema.Elements.Values

            ' If the qualified name of the element is "Customer", 
            ' get the complex type of the Customer element  
            ' and the sequence particle of the complex type.
            If element.QualifiedName.Name.Equals("Customer") Then

                Dim customerType As XmlSchemaComplexType = _
                    CType(element.ElementSchemaType, XmlSchemaComplexType)
                Dim sequence As XmlSchemaSequence = _
                    CType(customerType.Particle, XmlSchemaSequence)

                ' Add the new PhoneNumber element to the sequence.
                sequence.Items.Add(phoneElement)
            End If
        Next

        ' Reprocess and compile the modified XmlSchema object and write it to the console.
        schemaSet.Reprocess(customerSchema)
        schemaSet.Compile()
        customerSchema.Write(Console.Out)
    End Sub

    Shared Sub ValidationCallback(ByVal sender As Object, ByVal args As ValidationEventArgs)
        If args.Severity = XmlSeverityType.Warning Then
            Console.Write("WARNING: ")
        Else
            If args.Severity = XmlSeverityType.Error Then
                Console.Write("ERROR: ")
            End If
        End If
        Console.WriteLine(args.Message)
    End Sub

End Class

Berikut ini adalah skema pelanggan yang dimodifikasi yang dibuat dalam topik Membangun Skema XML .

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:tns="http://www.tempuri.org" targetNamespace="http://www.tempuri.org" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Customer">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="FirstName" type="xs:string" />
        <xs:element name="LastName" type="tns:LastNameType" />
        <xs:element name="PhoneNumber">           <xs:simpleType>             <xs:restriction base="xs:string">               <xs:pattern value="\d{3}-\d{3}-\d(4)" />             </xs:restriction>           </xs:simpleType>         </xs:element>
      </xs:sequence>
      <xs:attribute name="CustomerId" type="xs:positiveInteger" use="required" />
    </xs:complexType>
  </xs:element>
  <xs:simpleType name="LastNameType">
    <xs:restriction base="xs:string">
      <xs:maxLength value="20" />
    </xs:restriction>
  </xs:simpleType>
</xs:schema>

Contoh Atribut Judul

Contoh kode kedua ini, menambahkan atribut baru Title ke FirstName elemen skema pelanggan. Dalam contoh kode pertama, jenis FirstName elemennya adalah xs:string. FirstName Agar elemen memiliki atribut bersama dengan konten string, jenisnya harus diubah ke jenis kompleks dengan model konten ekstensi konten sederhana.

Contoh kode mengedit skema pelanggan dalam langkah-langkah berikut.

  1. Menambahkan skema pelanggan ke objek baru XmlSchemaSet lalu mengkompilasinya. Setiap peringatan validasi skema dan kesalahan yang ditemui saat membaca atau mengkompilasi skema ditangani oleh ValidationEventHandler delegasi.

  2. Mengambil objek yang dikompilasi XmlSchema dari XmlSchemaSet dengan melakukan iterasi melalui properti Schemas. Karena skema dikompilasi, properti Post-Schema-Compilation-Infoset (PSCI) dapat diakses.

  3. Membuat jenis kompleks baru untuk FirstName elemen menggunakan XmlSchemaComplexType kelas .

  4. Membuat ekstensi konten sederhana baru, dengan xs:string sebagai tipe dasar, menggunakan kelas XmlSchemaSimpleContent dan XmlSchemaSimpleContentExtension.

  5. Membuat atribut baru Title menggunakan kelas XmlSchemaAttribute, dengan SchemaTypeName dari xs:string dan menambahkan atribut tersebut ke ekstensi konten sederhana.

  6. Mengatur model konten konten sederhana ke ekstensi konten sederhana dan model konten jenis kompleks ke konten sederhana.

  7. Menambahkan tipe kompleks baru ke dalam koleksi skema sebelum kompilasi XmlSchema.Items.

  8. Melakukan iterasi pada masing-masing XmlSchemaObject dalam koleksi skema pra-kompilasi XmlSchema.Items.

Nota

FirstName Karena elemen bukan elemen global dalam skema, elemen tersebut tidak tersedia dalam XmlSchema.Items koleksi atau XmlSchema.Elements . Contoh kode menemukan FirstName elemen dengan terlebih dahulu menemukan Customer elemen .

Contoh kode pertama melintasi skema menggunakan sekumpulan data pasca kompilasi skema XmlSchema.Elements. Dalam contoh ini, kumpulan pra-kompilasi skema XmlSchema.Items digunakan untuk menjelajahi skema. Meskipun kedua koleksi menyediakan akses ke elemen global dalam skema, iterasi melalui Items koleksi lebih memakan waktu karena Anda harus melakukan iterasi atas semua elemen global dalam skema dan tidak memiliki properti PSCI. Koleksi PSCI (XmlSchema.Elements, XmlSchema.Attributes, , XmlSchema.SchemaTypesdan sebagainya) menyediakan akses langsung ke elemen, atribut, dan jenis global mereka dan properti PSCI mereka.

  1. Jika XmlSchemaObject adalah sebuah elemen, di mana QualifiedName adalah "Customer", dapatkan tipe kompleks dari elemen Customer menggunakan kelas XmlSchemaComplexType, dan partikel urutan dari tipe kompleks menggunakan kelas XmlSchemaSequence.

  2. Melakukan iterasi pada masing-masing XmlSchemaParticle dalam koleksi skema pra-kompilasi XmlSchemaSequence.Items.

  3. Jika XmlSchemaParticle adalah elemen yang QualifiedName adalah "FirstName", menetapkan SchemaTypeName dari elemen FirstName ke jenis kompleks baru FirstName.

  4. Terakhir, proses ulang dan kompilasi objek yang dimodifikasi XmlSchema menggunakan metode Reprocess dan Compile dari kelas XmlSchemaSet lalu menulisnya ke konsol.

Berikut ini adalah contoh kode lengkap.

using System;
using System.Xml;
using System.Xml.Schema;

class XmlSchemaEditExample
{
    static void Main(string[] args)
    {
        // Add the customer schema to a new XmlSchemaSet and compile it.
        // Any schema validation warnings and errors encountered reading or
        // compiling the schema are handled by the ValidationEventHandler delegate.
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
        schemaSet.Add("http://www.tempuri.org", "customer.xsd");
        schemaSet.Compile();

        // Retrieve the compiled XmlSchema object from the XmlSchemaSet
        // by iterating over the Schemas property.
        XmlSchema customerSchema = null;
        foreach (XmlSchema schema in schemaSet.Schemas())
        {
            customerSchema = schema;
        }

        // Create a complex type for the FirstName element.
        XmlSchemaComplexType complexType = new XmlSchemaComplexType();
        complexType.Name = "FirstNameComplexType";

        // Create a simple content extension with a base type of xs:string.
        XmlSchemaSimpleContent simpleContent = new XmlSchemaSimpleContent();
        XmlSchemaSimpleContentExtension simpleContentExtension =
            new XmlSchemaSimpleContentExtension();
        simpleContentExtension.BaseTypeName =
            new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

        // Create the new Title attribute with a SchemaTypeName of xs:string
        // and add it to the simple content extension.
        XmlSchemaAttribute attribute = new XmlSchemaAttribute();
        attribute.Name = "Title";
        attribute.SchemaTypeName =
            new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
        simpleContentExtension.Attributes.Add(attribute);

        // Set the content model of the simple content to the simple content extension
        // and the content model of the complex type to the simple content.
        simpleContent.Content = simpleContentExtension;
        complexType.ContentModel = simpleContent;

        // Add the new complex type to the pre-schema-compilation Items collection.
        customerSchema.Items.Add(complexType);

        // Iterate over each XmlSchemaObject in the pre-schema-compilation
        // Items collection.
        foreach (XmlSchemaObject schemaObject in customerSchema.Items)
        {
            // If the XmlSchemaObject is an element, whose QualifiedName
            // is "Customer", get the complex type of the Customer element
            // and the sequence particle of the complex type.
            if (schemaObject is XmlSchemaElement)
            {
                XmlSchemaElement element = schemaObject as XmlSchemaElement;

                if (element.QualifiedName.Name.Equals("Customer"))
                {
                    XmlSchemaComplexType customerType =
                        element.ElementSchemaType as XmlSchemaComplexType;

                    XmlSchemaSequence sequence =
                        customerType.Particle as XmlSchemaSequence;

                    // Iterate over each XmlSchemaParticle in the pre-schema-compilation
                    // Items property.
                    foreach (XmlSchemaParticle particle in sequence.Items)
                    {
                        // If the XmlSchemaParticle is an element, who's QualifiedName
                        // is "FirstName", set the SchemaTypeName of the FirstName element
                        // to the new FirstName complex type.
                        if (particle is XmlSchemaElement)
                        {
                            XmlSchemaElement childElement =
                                particle as XmlSchemaElement;

                            if (childElement.Name.Equals("FirstName"))
                            {
                                childElement.SchemaTypeName =
                                    new XmlQualifiedName("FirstNameComplexType",
                                    "http://www.tempuri.org");
                            }
                        }
                    }
                }
            }
        }

        // Reprocess and compile the modified XmlSchema object and write it to the console.
        schemaSet.Reprocess(customerSchema);
        schemaSet.Compile();
        customerSchema.Write(Console.Out);
    }

    static void ValidationCallback(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.Write("WARNING: ");
        else if (args.Severity == XmlSeverityType.Error)
            Console.Write("ERROR: ");

        Console.WriteLine(args.Message);
    }
}
Imports System.Xml
Imports System.Xml.Schema

Class XmlSchemaEditExample

    Shared Sub Main()

        ' Add the customer schema to a new XmlSchemaSet and compile it.
        ' Any schema validation warnings and errors encountered reading or 
        ' compiling the schema are handled by the ValidationEventHandler delegate.
        Dim schemaSet As XmlSchemaSet = New XmlSchemaSet()
        AddHandler schemaSet.ValidationEventHandler, AddressOf ValidationCallback
        schemaSet.Add("http://www.tempuri.org", "customer.xsd")
        schemaSet.Compile()

        ' Retrieve the compiled XmlSchema object from the XmlSchemaSet
        ' by iterating over the Schemas property.
        Dim customerSchema As XmlSchema = Nothing
        For Each schema As XmlSchema In schemaSet.Schemas()
            customerSchema = schema
        Next

        ' Create a complex type for the FirstName element.
        Dim complexType As XmlSchemaComplexType = New XmlSchemaComplexType()
        complexType.Name = "FirstNameComplexType"

        ' Create a simple content extension with a base type of xs:string.
        Dim simpleContent As XmlSchemaSimpleContent = New XmlSchemaSimpleContent()
        Dim simpleContentExtension As XmlSchemaSimpleContentExtension = _
            New XmlSchemaSimpleContentExtension()
        simpleContentExtension.BaseTypeName = _
            New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")

        ' Create the new Title attribute with a SchemaTypeName of xs:string
        ' and add it to the simple content extension.
        Dim attribute As XmlSchemaAttribute = New XmlSchemaAttribute()
        attribute.Name = "Title"
        attribute.SchemaTypeName = _
            New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
        simpleContentExtension.Attributes.Add(attribute)

        ' Set the content model of the simple content to the simple content extension
        ' and the content model of the complex type to the simple content.
        simpleContent.Content = simpleContentExtension
        complexType.ContentModel = simpleContent

        ' Add the new complex type to the pre-schema-compilation Items collection.
        customerSchema.Items.Add(complexType)

        ' Iterate over each XmlSchemaObject in the pre-schema-compilation
        ' Items collection.
        For Each schemaObject As XmlSchemaObject In customerSchema.Items

            ' If the XmlSchemaObject is an element, whose QualifiedName
            ' is "Customer", get the complex type of the Customer element
            ' and the sequence particle of the complex type.
            If schemaObject.GetType() Is GetType(XmlSchemaElement) Then

                Dim element As XmlSchemaElement = CType(schemaObject, XmlSchemaElement)

                If (element.QualifiedName.Name.Equals("Customer")) Then
                    Dim customerType As XmlSchemaComplexType = _
                        CType(element.ElementSchemaType, XmlSchemaComplexType)

                    Dim sequence As XmlSchemaSequence = _
                       CType(customerType.Particle, XmlSchemaSequence)

                    ' Iterate over each XmlSchemaParticle in the pre-schema-compilation
                    ' Items property.
                    For Each particle As XmlSchemaParticle In sequence.Items

                        ' If the XmlSchemaParticle is an element, who's QualifiedName
                        ' is "FirstName", set the SchemaTypeName of the FirstName element
                        ' to the new FirstName complex type.
                        If particle.GetType() Is GetType(XmlSchemaElement) Then
                            Dim childElement As XmlSchemaElement = _
                                CType(particle, XmlSchemaElement)

                            If childElement.Name.Equals("FirstName") Then
                                childElement.SchemaTypeName = _
                                   New XmlQualifiedName("FirstNameComplexType", _
                                  "http://www.tempuri.org")
                            End If
                        End If
                    Next
                End If
            End If
        Next

        ' Reprocess and compile the modified XmlSchema object and write it to the console.
        schemaSet.Reprocess(customerSchema)
        schemaSet.Compile()
        customerSchema.Write(Console.Out)
    End Sub

    Shared Sub ValidationCallback(ByVal sender As Object, ByVal args As ValidationEventArgs)
        If args.Severity = XmlSeverityType.Warning Then
            Console.Write("WARNING: ")
        Else
            If args.Severity = XmlSeverityType.Error Then
                Console.Write("ERROR: ")
            End If
        End If
        Console.WriteLine(args.Message)
    End Sub

End Class

Berikut ini adalah skema pelanggan yang dimodifikasi yang dibuat dalam topik Membangun Skema XML .

<?xml version="1.0" encoding=" utf-8"?>
<xs:schema xmlns:tns="http://www.tempuri.org" targetNamespace="http://www.tempuri.org" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Customer">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="FirstName" type="tns:FirstNameComplexType" />
        <xs:element name="LastName" type="tns:LastNameType" />
      </xs:sequence>
      <xs:attribute name="CustomerId" type="xs:positiveInteger" use="required" />
    </xs:complexType>
  </xs:element>
  <xs:simpleType name="LastNameType">
    <xs:restriction base="xs:string">
      <xs:maxLength value="20" />
    </xs:restriction>
  </xs:simpleType>
  <xs:complexType name="FirstNameComplexType">     <xs:simpleContent>       <xs:extension base="xs:string">         <xs:attribute name="Title" type="xs:string" />       </xs:extension>     </xs:simpleContent>   </xs:complexType>
</xs:schema>

Lihat juga