Not
Åtkomst till denna sida kräver auktorisation. Du kan prova att logga in eller byta katalog.
Åtkomst till denna sida kräver auktorisation. Du kan prova att byta katalog.
Redigering av ett XML-schema är en av de viktigaste funktionerna i Schema Object Model (SOM). Alla förschemakompileringsegenskaper för SOM kan användas för att ändra befintliga värden i ett XML-schema. XML-schemat kan sedan kompileras om för att återspegla ändringarna.
Det första steget i att redigera ett schema som läses in i SOM är att bläddra i schemat. Du bör vara bekant med att bläddra i ett schema med HJÄLP av SOM-API:et innan du försöker redigera ett schema. Du bör också känna till för- och efterschemakompileringsegenskaperna för PSCI (Post-Schema-Compilation-Infoset).
Redigera ett XML-schema
I det här avsnittet tillhandahålls två kodexempel, som båda redigerar kundschemat som skapades i avsnittet Skapa XML-scheman . Det första kodexemplet lägger till ett nytt PhoneNumber element i elementet Customer och det andra kodexemplet lägger till ett nytt Title attribut i elementet FirstName . Det första exemplet använder också samlingen efter schemakompilering XmlSchema.Elements som ett sätt att bläddra i kundschemat medan det andra kodexemplet använder samlingen pre-schema-compilation XmlSchema.Items .
Exempel på PhoneNumber-element
Det första kodexemplet lägger till ett nytt PhoneNumber element i elementet Customer i kundschemat. Kodexemplet redigerar kundschemat i följande steg.
Lägger till kundschemat i ett nytt XmlSchemaSet objekt och kompilerar det sedan. Eventuella schemavalideringsvarningar och fel som påträffades när schemat lästes eller kompilerades hanteras av ValidationEventHandler ombud.
Hämtar det kompilerade XmlSchema-objektet från XmlSchemaSet genom att iterera över egenskapen Schemas. Eftersom schemat kompileras är PSCI-egenskaper (Post-Schema-Compilation-Infoset) tillgängliga.
Skapar
PhoneNumber-elementet med hjälp av XmlSchemaElement-klassen, använderxs:stringför att definiera en enkel typbegränsning med XmlSchemaSimpleType- och XmlSchemaSimpleTypeRestriction-klasserna, lägger till en mönsterfacett i Facets-egenskapen hos begränsningen, och lägger till begränsningen i Content-egenskapen för den enkla typen samt placerar den enkla typen i SchemaType hosPhoneNumber-elementet.Itererar över varje XmlSchemaElement i Values-samlingen av post-schema-kompilering XmlSchema.Elements-samlingen.
Om elementets QualifiedName är
"Customer", hämtar den den komplexa typen avCustomer-elementet med hjälp av XmlSchemaComplexType-klassen och sekvenspartikeln av den komplexa typen med hjälp av XmlSchemaSequence-klassen.Lägger till det nya
PhoneNumber-elementet i sekvensen som redan innehåller de befintligaFirstName- ochLastName-elementen, med hjälp av den för-schemakompilering Items-samling som hör till sekvensen.Slutligen bearbetar och kompilerar de det ändrade XmlSchema-objektet med hjälp av Reprocess och Compile metoderna i XmlSchemaSet-klassen och skriver det till konsolen.
Följande är det fullständiga kodexemplet.
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
Följande är det ändrade kundschemat som skapades i artikeln Skapa XML-scheman .
<?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>
Exempel på rubrikattribut
Det här andra kodexemplet lägger till ett nytt Title attribut i elementet FirstName i kundschemat. I det första kodexemplet är typen av FirstName-elementet xs:string. För att elementet FirstName ska ha ett attribut tillsammans med stränginnehåll måste dess typ ändras till en komplex typ med en enkel innehållstilläggsinnehållsmodell.
Kodexemplet redigerar kundschemat i följande steg.
Lägger till kundschemat i ett nytt XmlSchemaSet objekt och kompilerar det sedan. Eventuella schemavalideringsvarningar och fel som påträffades när schemat lästes eller kompilerades hanteras av ValidationEventHandler ombud.
Hämtar det kompilerade XmlSchema-objektet från XmlSchemaSet genom att iterera över egenskapen Schemas. Eftersom schemat kompileras är PSCI-egenskaper (Post-Schema-Compilation-Infoset) tillgängliga.
Skapar en ny komplex typ för elementet
FirstNamemed hjälp av XmlSchemaComplexType -klassen.Skapar ett nytt enkelt innehållstillägg med bastypen
xs:string, med klasserna XmlSchemaSimpleContent och XmlSchemaSimpleContentExtension .Skapar det nya
Titleattributet med hjälp av XmlSchemaAttribute klassen, med ett SchemaTypeName påxs:string, och lägger till attributet till det enkla innehållstillägget.Anger innehållsmodellen för det enkla innehållet till det enkla innehållstillägget och innehållsmodellen av den komplexa typen till det enkla innehållet.
Lägger till den nya komplexa typen till samlingen för för-schemakompilering XmlSchema.Items.
Itererar över var och en XmlSchemaObject i samlingen före schemakompilering XmlSchema.Items.
Anmärkning
Eftersom elementet FirstName inte är ett globalt element i schemat är det inte tillgängligt i samlingarna XmlSchema.Items eller XmlSchema.Elements . Kodexemplet letar upp elementet FirstName genom att först hitta elementet Customer .
Det första kodexemplet passerade schemat med samlingen post-schema-compilation XmlSchema.Elements . I det här exemplet används samlingen för schemakompilering XmlSchema.Items för att bläddra i schemat. Båda samlingarna ger åtkomst till de globala elementen i schemat, men iterering via Items samlingen är mer tidskrävande eftersom du måste iterera över alla globala element i schemat och inte har några PSCI-egenskaper. PSCI-samlingarna (XmlSchema.Elements, XmlSchema.Attributes, XmlSchema.SchemaTypesoch så vidare) ger direkt åtkomst till deras globala element, attribut och typer och deras PSCI-egenskaper.
Om XmlSchemaObject är ett element, vars QualifiedName är
"Customer", hämtar den komplexa typen avCustomerelementet med hjälp av XmlSchemaComplexType klassen och sekvenspartikeln av den komplexa typen med hjälp av XmlSchemaSequence klassen.Itererar över var och en XmlSchemaParticle i samlingen före schemakompilering XmlSchemaSequence.Items.
XmlSchemaParticle är ett element, vars QualifiedName är
"FirstName", sätter SchemaTypeName-elementetsFirstNametill den nya komplexa typenFirstName.Slutligen bearbetar och kompilerar de det ändrade XmlSchema-objektet med hjälp av Reprocess och Compile metoderna i XmlSchemaSet-klassen och skriver det till konsolen.
Följande är det fullständiga kodexemplet.
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
Följande är det ändrade kundschemat som skapades i artikeln Skapa XML-scheman .
<?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>