Procházení schémat XML
Procházení schématu XML pomocí rozhraní API modelu objektu schématu (SOM) poskytuje přístup k prvkům, atributům a typům uloženým v SOM. Procházení schématu XML načteného do SOM je také prvním krokem při úpravě schématu XML pomocí rozhraní SOM API.
Následující vlastnosti třídy XmlSchema poskytují přístup ke kolekci všech globálních položek přidaných do schématu XML.
Vlastnictví | Typ objektu uložený v kolekci nebo poli |
---|---|
Elements | XmlSchemaElement |
Attributes | XmlSchemaAttribute |
AttributeGroups | XmlSchemaAttributeGroup |
Groups | XmlSchemaGroup |
Includes | XmlSchemaExternal, XmlSchemaInclude, XmlSchemaImportnebo XmlSchemaRedefine |
Items | XmlSchemaObject (poskytuje přístup ke všem prvkům globální úrovně, atributům a typům). |
Notations | XmlSchemaNotation |
SchemaTypes | XmlSchemaType, XmlSchemaSimpleType, XmlSchemaComplexType |
UnhandledAttributes | XmlAttribute (poskytuje přístup k atributům, které nepatří do oboru názvů schématu) |
Poznámka
Všechny vlastnosti uvedené v tabulce výše, s výjimkou vlastnosti Items, jsou vlastnosti Post-Schema-Compilation-Infoset (PSCI), které nejsou k dispozici, dokud nebude schéma zkompilováno. Vlastnost Items je vlastnost před kompilací schématu, kterou lze použít před kompilací schématu pro přístup k prvkům, atributům a typům globální úrovně a jejich úpravám.
Vlastnost UnhandledAttributes poskytuje přístup ke všem atributům, které nepatří do oboru názvů schématu. Tyto atributy procesor schématu nezpracovávají.
Následující příklad kódu ukazuje procházení schématu zákazníka vytvořeného v tématu Sestavení schémat XML. Příklad kódu ukazuje procházení schématu pomocí výše popsaných kolekcí a zapíše všechny prvky a atributy ve schématu do konzoly.
Ukázka prochází schématem zákazníka v následujících krocích.
Přidá schéma zákazníka do nového objektu XmlSchemaSet a pak ho zkompiluje. Všechna upozornění na ověření schématu a chyby, ke kterým došlo při čtení nebo kompilaci schématu, zpracovává ValidationEventHandler delegát.
Načte zkompilovaný objekt XmlSchema z XmlSchemaSet iterováním přes vlastnost Schemas. Vzhledem k tomu, že je schéma zkompilováno, jsou vlastnosti Post-Schema-Compilation-Infoset (PSCI) přístupné.
Iteruje přes každý XmlSchemaElement v kolekci Values v kolekci XmlSchema.Elements po kompilaci schématu a zapisuje název každého prvku do konzoly.
Získá komplexní typ elementu
Customer
pomocí třídy XmlSchemaComplexType.Pokud má komplexní typ nějaké atributy, získá IDictionaryEnumerator pro výčet každého XmlSchemaAttribute a zapíše jeho název do konzoly.
Získá částici sekvence komplexního typu pomocí třídy XmlSchemaSequence.
Iteruje přes každou XmlSchemaElement v kolekci XmlSchemaSequence.Items a zapíše název každého podřízeného prvku na konzoli.
Následuje kompletní příklad kódu.
#using <System.Xml.dll>
using namespace System;
using namespace System::Collections;
using namespace System::Xml;
using namespace System::Xml::Schema;
ref class XmlSchemaTraverseExample
{
public:
static void 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.
XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet();
schemaSet->ValidationEventHandler += gcnew 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 = nullptr;
for each (XmlSchema^ schema in schemaSet->Schemas())
{
customerSchema = schema;
}
// Iterate over each XmlSchemaElement in the Values collection
// of the Elements property.
for each (XmlSchemaElement^ element in customerSchema->Elements->Values)
{
Console::WriteLine("Element: {0}", element->Name);
// Get the complex type of the Customer element.
XmlSchemaComplexType^ complexType = dynamic_cast<XmlSchemaComplexType^>(element->ElementSchemaType);
// If the complex type has any attributes, get an enumerator
// and write each attribute name to the console.
if (complexType->AttributeUses->Count > 0)
{
IDictionaryEnumerator^ enumerator =
complexType->AttributeUses->GetEnumerator();
while (enumerator->MoveNext())
{
XmlSchemaAttribute^ attribute =
dynamic_cast<XmlSchemaAttribute^>(enumerator->Value);
Console::WriteLine("Attribute: {0}", attribute->Name);
}
}
// Get the sequence particle of the complex type.
XmlSchemaSequence^ sequence = dynamic_cast<XmlSchemaSequence^>(complexType->ContentTypeParticle);
// Iterate over each XmlSchemaElement in the Items collection.
for each (XmlSchemaElement^ childElement in sequence->Items)
{
Console::WriteLine("Element: {0}", childElement->Name);
}
}
}
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);
}
};
int main()
{
XmlSchemaTraverseExample::Main();
return 0;
};
using System;
using System.Collections;
using System.Xml;
using System.Xml.Schema;
class XmlSchemaTraverseExample
{
static void 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.
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;
}
// Iterate over each XmlSchemaElement in the Values collection
// of the Elements property.
foreach (XmlSchemaElement element in customerSchema.Elements.Values)
{
Console.WriteLine($"Element: {element.Name}");
// Get the complex type of the Customer element.
XmlSchemaComplexType complexType = element.ElementSchemaType as XmlSchemaComplexType;
// If the complex type has any attributes, get an enumerator
// and write each attribute name to the console.
if (complexType.AttributeUses.Count > 0)
{
IDictionaryEnumerator enumerator =
complexType.AttributeUses.GetEnumerator();
while (enumerator.MoveNext())
{
XmlSchemaAttribute attribute =
(XmlSchemaAttribute)enumerator.Value;
Console.WriteLine($"Attribute: {attribute.Name}");
}
}
// Get the sequence particle of the complex type.
XmlSchemaSequence sequence = complexType.ContentTypeParticle as XmlSchemaSequence;
// Iterate over each XmlSchemaElement in the Items collection.
foreach (XmlSchemaElement childElement in sequence.Items)
{
Console.WriteLine($"Element: {childElement.Name}");
}
}
}
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.Collections
Imports System.Xml
Imports System.Xml.Schema
Class XmlSchemaTraverseExample
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
' Iterate over each XmlSchemaElement in the Values collection
' of the Elements property.
For Each element As XmlSchemaElement In customerSchema.Elements.Values
Console.WriteLine("Element: {0}", element.Name)
' Get the complex type of the Customer element.
Dim complexType As XmlSchemaComplexType = CType(element.ElementSchemaType, XmlSchemaComplexType)
' If the complex type has any attributes, get an enumerator
' and write each attribute name to the console.
If complexType.AttributeUses.Count > 0 Then
Dim enumerator As IDictionaryEnumerator = _
complexType.AttributeUses.GetEnumerator()
While enumerator.MoveNext()
Dim attribute As XmlSchemaAttribute = _
CType(enumerator.Value, XmlSchemaAttribute)
Console.WriteLine("Attribute: {0}", Attribute.Name)
End While
End If
' Get the sequence particle of the complex type.
Dim sequence As XmlSchemaSequence = CType(complexType.ContentTypeParticle, XmlSchemaSequence)
For Each childElement As XmlSchemaElement In sequence.Items
Console.WriteLine("Element: {0}", childElement.Name)
Next
Next
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
Vlastnost XmlSchemaElement.ElementSchemaType může být XmlSchemaSimpleTypenebo XmlSchemaComplexType, pokud se jedná o uživatelem definovaný jednoduchý typ nebo komplexní typ. Může to být také XmlSchemaDatatype, pokud se jedná o jeden z předdefinovaných datových typů dle doporučení W3C XML Schema. Ve schématu zákazníka je ElementSchemaType elementu Customer
XmlSchemaComplexTypea prvky FirstName
a LastName
jsou XmlSchemaSimpleType.
Příklad kódu v tématu Sestavení schémat XML použil kolekci XmlSchemaComplexType.Attributes k přidání atributu CustomerId
do elementu Customer
. Toto je vlastnost před kompilací schématu. Odpovídající vlastností Post-Schema-Compilation-Infoset je kolekce XmlSchemaComplexType.AttributeUses, která obsahuje všechny atributy komplexního typu, včetně těch, které jsou děděny prostřednictvím odvození typu.
- Přehled modelu objektu schématu XML
- čtení a zápis schémat XML
- vytváření schémat XML
- úpravy schémat XML
- Vložení nebo importování schémat XML
- XmlSchemaSet pro kompilaci schémat
- Infoset po kompilaci schématu
Zpětná vazba k produktu .NET
.NET je open source projekt. Vyberte odkaz pro poskytnutí zpětné vazby: