Hinweis
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, sich anzumelden oder das Verzeichnis zu wechseln.
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, das Verzeichnis zu wechseln.
Das Bearbeiten eines XML-Schemas ist eines der wichtigsten Features des Schemaobjektmodells (SOM). Alle Vorabschemakompilierungseigenschaften des SOM können verwendet werden, um die vorhandenen Werte in einem XML-Schema zu ändern. Das XML-Schema kann dann neu kompiliert werden, um die Änderungen widerzuspiegeln.
Der erste Schritt beim Bearbeiten eines in das SOM geladenen Schemas besteht darin, das Schema zu durchlaufen. Sie sollten mit dem Durchlaufen eines Schemas mithilfe der SOM-API vertraut sein, bevor Sie versuchen, ein Schema zu bearbeiten. Sie sollten auch mit den Eigenschaften der Vor- und Nach-Schema-Kompilierung des Post-Schema-Compilation-Infoset (PSCI) vertraut sein.
Bearbeiten eines XML-Schemas
In diesem Abschnitt werden zwei Codebeispiele bereitgestellt, die beide das kundenschema bearbeiten, das im Thema "Building XML Schemas " erstellt wurde. Im ersten Codebeispiel wird dem PhoneNumber Element ein neues Customer Element hinzugefügt, und im zweiten Codebeispiel wird dem Title Element ein neues FirstName Attribut hinzugefügt. Im ersten Beispiel wird die Sammlung nach der Schemakompilierung XmlSchema.Elements auch als Mittel zum Durchlaufen des Kundenschemas verwendet, während im zweiten Codebeispiel die Sammlung vor der Schemakompilierung XmlSchema.Items verwendet wird.
PhoneNumber-Element (Beispiel)
In diesem ersten Codebeispiel wird dem PhoneNumber Element des Kundenschemas ein neues Customer Element hinzugefügt. Im Codebeispiel wird das Kundenschema in den folgenden Schritten bearbeitet.
Fügt das Kundenschema zu einem neuen XmlSchemaSet Objekt hinzu und kompiliert es. Alle Warnungen und Fehler bei der Schemaüberprüfung, die beim Lesen oder Kompilieren des Schemas aufgetreten sind, werden vom ValidationEventHandler Delegat behandelt.
Ruft das kompilierte XmlSchema Objekt aus dem XmlSchemaSet durch Durchlaufen der Schemas Eigenschaft ab. Da das Schema kompiliert ist, sind die Post-Schema-Compilation-Infoset (PSCI)-Eigenschaften zugänglich.
Erstellt das
PhoneNumber-Element mithilfe der XmlSchemaElement-Klasse, diexs:string-Einschränkung des einfachen Typs mithilfe der XmlSchemaSimpleType- und XmlSchemaSimpleTypeRestriction-Klassen, fügt der Facets-Eigenschaft der Einschränkung ein Muster-Facet hinzu und fügt die Einschränkung der Content-Eigenschaft des einfachen Typs hinzu und den einfachen Typ dem SchemaType-PhoneNumber-Element.Iteriert über jedes XmlSchemaElement in der Values Sammlung der post-Schemakompilierung XmlSchema.Elements Sammlung.
Wenn das QualifiedName-Element
"Customer"ist, ruft es den komplexen Typ desCustomer-Elements mit der XmlSchemaComplexType-Klasse ab und die Sequenzpartikel des komplexen Typs mithilfe der XmlSchemaSequence-Klasse.Fügt das neue
PhoneNumber-Element der Sequenz hinzu, die die vorhandenenFirstName- undLastName-Elemente enthält, unter Verwendung der Vorabschemakompilierungsauflistung Items der Sequenz.Schließlich wird das geänderte XmlSchema-Objekt mithilfe der Reprocess- und Compile-Methoden der XmlSchemaSet-Klasse neu verarbeitet und kompiliert und in die Konsole geschrieben.
Im Folgenden sehen Sie das vollständige Codebeispiel.
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
Nachfolgend sehen Sie das geänderte Kundenschema, das im Thema "Building XML Schemas" erstellt wurde.
<?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>
Title-Attribut (Beispiel)
In diesem zweiten Codebeispiel wird dem Title Element des Kundenschemas ein neues FirstName Attribut hinzugefügt. Im ersten Codebeispiel ist der Typ des FirstName Elements xs:string. Damit das FirstName Element ein Attribut zusammen mit Zeichenfolgeninhalt aufweist, muss der Typ in einen komplexen Typ mit einem einfachen Inhaltserweiterungs-Inhaltsmodell geändert werden.
Im Codebeispiel wird das Kundenschema in den folgenden Schritten bearbeitet.
Fügt das Kundenschema zu einem neuen XmlSchemaSet Objekt hinzu und kompiliert es. Alle Warnungen und Fehler bei der Schemaüberprüfung, die beim Lesen oder Kompilieren des Schemas aufgetreten sind, werden vom ValidationEventHandler Delegat behandelt.
Ruft das kompilierte XmlSchema Objekt aus dem XmlSchemaSet durch Durchlaufen der Schemas Eigenschaft ab. Da das Schema kompiliert ist, sind die Post-Schema-Compilation-Infoset (PSCI)-Eigenschaften zugänglich.
Erstellt einen neuen komplexen Typ für das
FirstNameElement mithilfe der XmlSchemaComplexType Klasse.Erstellt eine neue einfache Inhaltserweiterung mit einem Basistyp von
xs:string, wobei die Klassen XmlSchemaSimpleContent und XmlSchemaSimpleContentExtension verwendet werden.Erstellt das neue
TitleAttribut mithilfe der XmlSchemaAttribute Klasse mit einer SchemaTypeName vonxs:stringund fügt das Attribut der einfachen Inhaltserweiterung hinzu.Legt das Inhaltsmodell des einfachen Inhalts auf die einfache Inhaltserweiterung und das Inhaltsmodell des komplexen Typs auf den einfachen Inhalt fest.
Fügt den neuen komplexen Typ der Vorabschemakompilierungsauflistung XmlSchema.Items hinzu.
Iteriert über jedes XmlSchemaObject in der Vorab-Schema-Kompilierungssammlung XmlSchema.Items.
Hinweis
Da das FirstName-Element kein globales Element im Schema ist, ist es weder in den XmlSchema.Items-Sammlungen noch in den XmlSchema.Elements-Sammlungen verfügbar. Das Codebeispiel sucht das FirstName Element, indem zuerst das Customer Element gefunden wird.
Im ersten Codebeispiel wurde das Schema mithilfe der Nachschemakompilierungsauflistung XmlSchema.Elements durchlaufen. In diesem Beispiel wird die Vorabschemakompilierungsauflistung XmlSchema.Items verwendet, um das Schema zu durchlaufen. Beide Auflistungen bieten zwar Zugriff auf die globalen Elemente im Schema, das Durchlaufen der Items Auflistung ist jedoch zeitaufwändiger, da Sie alle globalen Elemente im Schema durchlaufen müssen und keine PSCI-Eigenschaften aufweisen. Die PSCI-Auflistungen (XmlSchema.Elements, XmlSchema.Attributes, XmlSchema.SchemaTypesusw.) bieten direkten Zugriff auf ihre globalen Elemente, Attribute und Typen sowie ihre PSCI-Eigenschaften.
Wenn das XmlSchemaObject ein Element ist, dessen QualifiedName
"Customer"ist, wird der komplexe Typ desCustomer-Elements mithilfe der XmlSchemaComplexType-Klasse und das Sequenzpartikel des komplexen Typs mithilfe der XmlSchemaSequence-Klasse abgerufen.Iteriert über jedes XmlSchemaParticle in der Vorab-Schema-Kompilierungssammlung XmlSchemaSequence.Items.
Wenn XmlSchemaParticle ein Element ist, dessen QualifiedName
"FirstName"ist, wird das SchemaTypeName desFirstName-Elements auf den neuen komplexen TypFirstNamefestgelegt.Schließlich wird das geänderte XmlSchema-Objekt mithilfe der Reprocess- und Compile-Methoden der XmlSchemaSet-Klasse neu verarbeitet und kompiliert und in die Konsole geschrieben.
Im Folgenden sehen Sie das vollständige Codebeispiel.
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
Nachfolgend sehen Sie das geänderte Kundenschema, das im Thema "Building XML Schemas" erstellt wurde.
<?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>