Extensions.Validate Méthode
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Valide qu’un XDocument, un XElementou un XAttribute objet est conforme à un XSD dans un XmlSchemaSet.
Surcharges
| Nom | Description |
|---|---|
| Validate(XDocument, XmlSchemaSet, ValidationEventHandler) |
Cette méthode valide qu’un XDocument XSD est conforme à un XSD dans un XmlSchemaSet. |
| Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler) |
Cette méthode valide qu’une XAttribute conformité à un élément spécifié XmlSchemaObject et un XmlSchemaSet. |
| Validate(XDocument, XmlSchemaSet, ValidationEventHandler, Boolean) |
Valide qu’un XDocument XSD est conforme à un XSD dans une XmlSchemaSetarborescence XML, éventuellement en remplit l’arborescence XML avec l’ensemble d’informations post-validation de schéma (PSVI). |
| Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler) |
Cette méthode valide qu’une XElement sous-arborescence est conforme à un objet spécifié XmlSchemaObject et un XmlSchemaSet. |
| Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler, Boolean) |
Valide qu’un XAttribute élément est conforme à un ensemble d’informations spécifié XmlSchemaObject et à un XmlSchemaSet, éventuellement en remplit l’arborescence XML avec l’ensemble d’informations post-validation de schéma (PSVI). |
| Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler, Boolean) |
Valide qu’une XElement sous-arborescence est conforme à un objet spécifié XmlSchemaObject et à une XmlSchemaSetarborescence XML , éventuellement en remplit l’arborescence XML avec l’ensemble d’informations post-validation de schéma (PSVI). |
Remarques
Ces méthodes utilisent un sous-jacent XmlReader pour valider l’arborescence XML sur un XSD.
Les messages d’erreur et d’avertissement de validation sont gérés à l’aide du ValidationEventHandler délégué. Si aucun gestionnaire d’événements n’est fourni à ces méthodes, les erreurs de validation sont exposées en tant que XmlSchemaValidationException. Les avertissements de validation n’entraînent pas de XmlSchemaValidationException levée.
Certaines de ces méthodes d’extension autorisent éventuellement la population de l’ensemble d’informations post-validation de schéma (PSVI).
Validate(XDocument, XmlSchemaSet, ValidationEventHandler)
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
Cette méthode valide qu’un XDocument XSD est conforme à un XSD dans un XmlSchemaSet.
public:
[System::Runtime::CompilerServices::Extension]
static void Validate(System::Xml::Linq::XDocument ^ source, System::Xml::Schema::XmlSchemaSet ^ schemas, System::Xml::Schema::ValidationEventHandler ^ validationEventHandler);
public static void Validate(this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler);
public static void Validate(this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler);
static member Validate : System.Xml.Linq.XDocument * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler -> unit
<Extension()>
Public Sub Validate (source As XDocument, schemas As XmlSchemaSet, validationEventHandler As ValidationEventHandler)
Paramètres
- schemas
- XmlSchemaSet
À XmlSchemaSet valider.
- validationEventHandler
- ValidationEventHandler
Pour ValidationEventHandler un événement qui se produit lorsque le lecteur rencontre des erreurs de validation. Si null, lève une exception lors d’erreurs de validation.
Exceptions
Levée pour les erreurs de validation XSD (XML Schema Definition Language).
Exemples
L’exemple suivant crée un XmlSchemaSetobjet, puis valide deux XDocument objets par rapport au jeu de schémas. L’un des documents est valide, l’autre n’est pas.
string xsdMarkup =
@"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='Child1' minOccurs='1' maxOccurs='1'/>
<xsd:element name='Child2' minOccurs='1' maxOccurs='1'/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>";
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));
XDocument doc1 = new XDocument(
new XElement("Root",
new XElement("Child1", "content1"),
new XElement("Child2", "content1")
)
);
XDocument doc2 = new XDocument(
new XElement("Root",
new XElement("Child1", "content1"),
new XElement("Child3", "content1")
)
);
Console.WriteLine("Validating doc1");
bool errors = false;
doc1.Validate(schemas, (o, e) =>
{
Console.WriteLine("{0}", e.Message);
errors = true;
});
Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");
Console.WriteLine();
Console.WriteLine("Validating doc2");
errors = false;
doc2.Validate(schemas, (o, e) =>
{
Console.WriteLine("{0}", e.Message);
errors = true;
});
Console.WriteLine("doc2 {0}", errors ? "did not validate" : "validated");
Dim errors As Boolean = False
Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)
Console.WriteLine("{0}", e.Message)
errors = True
End Sub
Sub Main()
Dim xsdMarkup As XDocument = _
<?xml version='1.0'?>
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='Child1' minOccurs='1' maxOccurs='1'/>
<xsd:element name='Child2' minOccurs='1' maxOccurs='1'/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Dim schemas As XmlSchemaSet = New XmlSchemaSet()
schemas.Add("", xsdMarkup.CreateReader)
Dim doc1 As XDocument = _
<?xml version='1.0'?>
<Root>
<Child1>content1</Child1>
<Child2>content2</Child2>
</Root>
Dim doc2 As XDocument = _
<?xml version='1.0'?>
<Root>
<Child1>content1</Child1>
<Child3>content1</Child3>
</Root>
Console.WriteLine("Validating doc1")
errors = False
doc1.Validate(schemas, AddressOf XSDErrors)
Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))
Console.WriteLine()
Console.WriteLine("Validating doc2")
errors = False
doc2.Validate(schemas, AddressOf XSDErrors)
Console.WriteLine("doc2 {0}", IIf(errors, "did not validate", "validated"))
End Sub
Cet exemple produit la sortie suivante :
Validating doc1
doc1 validated
Validating doc2
The element 'Root' has invalid child element 'Child3'. List of possible elements expected: 'Child2'.
doc2 did not validate
Remarques
Cette méthode d’extension valide que le XDocument modèle de contenu de schéma est conforme dans XmlSchemaSet.
S’applique à
Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
Cette méthode valide qu’une XAttribute conformité à un élément spécifié XmlSchemaObject et un XmlSchemaSet.
public:
[System::Runtime::CompilerServices::Extension]
static void Validate(System::Xml::Linq::XAttribute ^ source, System::Xml::Schema::XmlSchemaObject ^ partialValidationType, System::Xml::Schema::XmlSchemaSet ^ schemas, System::Xml::Schema::ValidationEventHandler ^ validationEventHandler);
public static void Validate(this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler);
public static void Validate(this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler);
static member Validate : System.Xml.Linq.XAttribute * System.Xml.Schema.XmlSchemaObject * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler -> unit
<Extension()>
Public Sub Validate (source As XAttribute, partialValidationType As XmlSchemaObject, schemas As XmlSchemaSet, validationEventHandler As ValidationEventHandler)
Paramètres
- source
- XAttribute
XAttribute À valider.
- partialValidationType
- XmlSchemaObject
Qui XmlSchemaObject spécifie la sous-arborescence à valider.
- schemas
- XmlSchemaSet
À XmlSchemaSet valider.
- validationEventHandler
- ValidationEventHandler
Pour ValidationEventHandler un événement qui se produit lorsque le lecteur rencontre des erreurs de validation. Si null, lève une exception lors d’erreurs de validation.
Exceptions
Levée pour les erreurs de validation XSD (XML Schema Definition Language).
Exemples
string xsdMarkup =
@"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base='xsd:string'>
<xsd:attribute name='Lang' use='required'>
<xsd:simpleType>
<xsd:restriction base='xsd:token'>
<xsd:enumeration value='C#'/>
<xsd:enumeration value='VB'/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
</xsd:schema>";
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));
XDocument doc1 = new XDocument(
new XElement("Root",
new XAttribute("Lang", "C#")
)
);
Console.WriteLine("Validating doc1 ...");
bool errors = false;
doc1.Validate(schemas, (sender, e) =>
{
Console.WriteLine(e.Message);
errors = true;
}, true);
Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");
Console.WriteLine();
Console.WriteLine("Validating Lang attribute ...");
XAttribute lang = doc1.Root.Attribute("Lang");
errors = false;
lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, (sender, e) =>
{
Console.WriteLine(e.Message);
errors = true;
});
Console.WriteLine("lang {0}", errors ? "did not validate" : "validated");
// the following makes the Lang attribute invalid according to the schema
lang.Value = "VC";
Console.WriteLine();
Console.WriteLine("Validating Lang attribute ...");
errors = false;
lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, (sender, e) =>
{
Console.WriteLine(e.Message);
errors = true;
});
Console.WriteLine("lang {0}", errors ? "did not validate" : "validated");
Dim errors As Boolean = False
Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)
Console.WriteLine("{0}", e.Message)
errors = True
End Sub
Sub Main()
Dim xsdMarkup As XDocument = _
<?xml version='1.0'?>
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base='xsd:string'>
<xsd:attribute name='Lang' use='required'>
<xsd:simpleType>
<xsd:restriction base='xsd:token'>
<xsd:enumeration value='C#'/>
<xsd:enumeration value='VB'/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Dim schemas As XmlSchemaSet = New XmlSchemaSet()
schemas.Add("", xsdMarkup.CreateReader)
Dim doc1 As XDocument = <?xml version='1.0'?>
<Root Lang='C#'/>
Console.WriteLine("Validating doc1 ...")
errors = False
doc1.Validate(schemas, AddressOf XSDErrors, True)
Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))
Console.WriteLine()
Console.WriteLine("Validating Lang attribute ...")
Dim lang As XAttribute = doc1.Root.Attribute("Lang")
errors = False
lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, AddressOf XSDErrors)
Console.WriteLine("lang {0}", IIf(errors, "did not validate", "validated"))
' the following makes the Lang attribute invalid according to the schema
lang.Value = "VC"
Console.WriteLine()
Console.WriteLine("Validating Lang attribute ...")
errors = False
lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, AddressOf XSDErrors)
Console.WriteLine("lang {0}", IIf(errors, "did not validate", "validated"))
End Sub
Cet exemple produit la sortie suivante :
Validating doc1 ...
doc1 validated
Validating Lang attribute ...
lang validated
Validating Lang attribute ...
The 'Lang' attribute is invalid - The value 'VC' is invalid according to its datatype 'Token' - The Enumeration constraint failed.
lang did not validate
Remarques
Vous pouvez utiliser cette méthode pour vérifier qu’un XAttribute schéma est conforme à un schéma. Vous utilisez généralement cette méthode lorsque vous avez modifié un attribut et que vous souhaitez vous assurer qu’il est toujours conforme à son schéma. Vous pouvez valider l’intégralité du document, mais il faut moins de temps de traitement pour valider uniquement l’attribut.
Si vous passez null , validationEventHandlercette méthode déclenche une exception lors des erreurs de validation. Les avertissements de validation ne déclenchent pas d’exception.
Pour valider un attribut, vous utilisez une instance de XmlSchemaObject. Vous pouvez obtenir cette instance de différentes façons. Un moyen simple est le suivant :
Vérifiez qu’un document est conforme à un schéma.
Ajoutez l’ensemble d’informations post-validation de schéma (PSVI) en appelant la méthode d’extension Validate .
Appelez la méthode d’extension GetSchemaInfo pour récupérer un objet qui implémente IXmlSchemaInfo. À partir de l’objet récupéré, vous pouvez obtenir un XmlSchemaObject.
Si vous obtenez un XmlSchemaObject pour un XElement, le type sera XmlSchemaElement.
Si vous obtenez un XmlSchemaObject pour un XAttribute, le type sera XmlSchemaAttribute.
Une fois que vous avez une instance d’un XmlSchemaObject, vous pouvez utiliser cette méthode pour valider un attribut.
S’applique à
Validate(XDocument, XmlSchemaSet, ValidationEventHandler, Boolean)
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
Valide qu’un XDocument XSD est conforme à un XSD dans une XmlSchemaSetarborescence XML, éventuellement en remplit l’arborescence XML avec l’ensemble d’informations post-validation de schéma (PSVI).
public:
[System::Runtime::CompilerServices::Extension]
static void Validate(System::Xml::Linq::XDocument ^ source, System::Xml::Schema::XmlSchemaSet ^ schemas, System::Xml::Schema::ValidationEventHandler ^ validationEventHandler, bool addSchemaInfo);
public static void Validate(this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler, bool addSchemaInfo);
public static void Validate(this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo);
static member Validate : System.Xml.Linq.XDocument * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler * bool -> unit
<Extension()>
Public Sub Validate (source As XDocument, schemas As XmlSchemaSet, validationEventHandler As ValidationEventHandler, addSchemaInfo As Boolean)
Paramètres
- schemas
- XmlSchemaSet
À XmlSchemaSet valider.
- validationEventHandler
- ValidationEventHandler
Pour ValidationEventHandler un événement qui se produit lorsque le lecteur rencontre des erreurs de validation. Si null, lève une exception lors d’erreurs de validation.
- addSchemaInfo
- Boolean
Indiquant Boolean s’il faut remplir l’ensemble d’informations post-validation de schéma (PSVI).
Exceptions
Levée pour les erreurs de validation XSD (XML Schema Definition Language).
Exemples
L’exemple suivant contient un XSD qui définit l’élément Child2 avec un Att1 attribut avec une valeur par défaut. Une fois le document validé, l’attribut avec la valeur par défaut est ajouté à l’arborescence XML. Notez que l’attribut par défaut n’est pas ajouté à doc2, ce qui ne valide pas par rapport au schéma.
string xsdMarkup =
@"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='Child1' minOccurs='1' maxOccurs='1'/>
<xsd:element name='Child2' minOccurs='1' maxOccurs='1'>
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base='xsd:string'>
<xsd:attribute name='Att1' default='Att1 Default Value'/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>";
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));
XDocument doc1 = new XDocument(
new XElement("Root",
new XElement("Child1", "c1"),
new XElement("Child2", "c2")
)
);
XDocument doc2 = new XDocument(
new XElement("Root",
new XElement("Child1", "content1"),
new XElement("Child3", "content1")
)
);
Console.WriteLine("Validating doc1");
bool errors = false;
doc1.Validate(schemas, (o, e) =>
{
Console.WriteLine("{0}", e.Message);
errors = true;
}, true);
Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");
Console.WriteLine();
Console.WriteLine("Validating doc2");
errors = false;
doc2.Validate(schemas, (o, e) =>
{
Console.WriteLine("{0}", e.Message);
errors = true;
}, true);
Console.WriteLine("doc2 {0}", errors ? "did not validate" : "validated");
Console.WriteLine();
Console.WriteLine("Contents of doc1:");
Console.WriteLine(doc1);
Console.WriteLine();
Console.WriteLine("Contents of doc2:");
Console.WriteLine(doc2);
Dim errors As Boolean = False
Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)
Console.WriteLine("{0}", e.Message)
errors = True
End Sub
Sub Main()
Dim xsdMarkup As XDocument = _
<?xml version='1.0'?>
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='Child1' minOccurs='1' maxOccurs='1'/>
<xsd:element name='Child2' minOccurs='1' maxOccurs='1'>
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base='xsd:string'>
<xsd:attribute name='Att1' default='Att1 Default Value'/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Dim schemas As XmlSchemaSet = New XmlSchemaSet()
schemas.Add("", xsdMarkup.CreateReader)
Dim doc1 As XDocument = <?xml version='1.0'?>
<Root>
<Child1>c1</Child1>
<Child2>c2</Child2>
</Root>
Dim doc2 As XDocument = <?xml version='1.0'?>
<Root>
<Child1>content1</Child1>
<Child3>content1</Child3>
</Root>
Console.WriteLine("Validating doc1")
errors = False
doc1.Validate(schemas, AddressOf XSDErrors, True)
Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))
Console.WriteLine()
Console.WriteLine("Validating doc2")
errors = False
doc2.Validate(schemas, AddressOf XSDErrors, True)
Console.WriteLine("doc2 {0}", IIf(errors, "did not validate", "validated"))
Console.WriteLine()
Console.WriteLine("Contents of doc1:")
Console.WriteLine(doc1)
Console.WriteLine()
Console.WriteLine("Contents of doc2:")
Console.WriteLine(doc2)
End Sub
Cet exemple produit la sortie suivante :
Validating doc1
doc1 validated
Validating doc2
The element 'Root' has invalid child element 'Child3'. List of possible elements expected: 'Child2'.
doc2 did not validate
Contents of doc1:
<Root>
<Child1>c1</Child1>
<Child2 Att1="Att1 Default Value">c2</Child2>
</Root>
Contents of doc2:
<Root>
<Child1>content1</Child1>
<Child3>content1</Child3>
</Root>
L’exemple suivant remplit l’arborescence avec PSVI. Après validation, il imprime tous les éléments et attributs de l’arborescence qui ne sont pas valides en fonction de PSVI.
static void DumpInvalidNodes(XElement el)
{
if (el.GetSchemaInfo().Validity != XmlSchemaValidity.Valid)
Console.WriteLine("Invalid Element {0}",
el.AncestorsAndSelf()
.InDocumentOrder()
.Aggregate("", (s, i) => s + "/" + i.Name.ToString()));
foreach (XAttribute att in el.Attributes())
if (att.GetSchemaInfo().Validity != XmlSchemaValidity.Valid)
Console.WriteLine("Invalid Attribute {0}",
att
.Parent
.AncestorsAndSelf()
.InDocumentOrder()
.Aggregate("",
(s, i) => s + "/" + i.Name.ToString()) + "/@" + att.Name.ToString()
);
foreach (XElement child in el.Elements())
DumpInvalidNodes(child);
}
static void Main(string[] args)
{
string xsdMarkup =
@"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:simpleType name='GCType'>
<xsd:restriction base='xsd:token'>
<xsd:enumeration value='AAA'/>
<xsd:enumeration value='BBB'/>
</xsd:restriction>
</xsd:simpleType>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='Child1' minOccurs='1' maxOccurs='1'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='GrandChild1' type='GCType'/>
<xsd:element name='GrandChild2' type='GCType'/>
<xsd:element name='GrandChild3' type='GCType'/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>";
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));
XDocument doc1 = new XDocument(
new XElement("Root",
new XElement("Child1",
new XElement("GrandChild1", "AAA"),
new XElement("GrandChild2", "ZZZ"),
new XElement("GrandChild3", "ZZZ")
)
)
);
Console.WriteLine("Validating doc1 ...");
bool errors = false;
doc1.Validate(schemas, (sender, e) =>
{
Console.WriteLine(e.Message);
errors = true;
}, true);
Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");
DumpInvalidNodes(doc1.Root);
}
Private Sub DumpInvalidNodes(ByVal el As XElement)
If el.GetSchemaInfo.Validity <> XmlSchemaValidity.Valid Then
Console.WriteLine("Invalid Element {0}", _
el _
.AncestorsAndSelf _
.InDocumentOrder() _
.Aggregate("", _
Function(ByVal s, ByVal i) s + "/" + i.Name.ToString()))
End If
For Each att As XAttribute In el.Attributes()
If att.GetSchemaInfo.Validity <> XmlSchemaValidity.Valid Then
Console.WriteLine("Invalid Attribute {0}", _
att _
.Parent _
.AncestorsAndSelf() _
.InDocumentOrder() _
.Aggregate("", _
Function(ByVal s, ByVal i) s + "/" + i.Name.ToString()) + _
"/@" + att.Name.ToString())
End If
Next
For Each child As XElement In el.Elements()
DumpInvalidNodes(child)
Next
End Sub
Dim errors As Boolean = False
Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)
Console.WriteLine("{0}", e.Message)
errors = True
End Sub
Sub Main()
Dim xsdMarkup As XDocument = _
<?xml version='1.0'?>
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:simpleType name='GCType'>
<xsd:restriction base='xsd:token'>
<xsd:enumeration value='AAA'/>
<xsd:enumeration value='BBB'/>
</xsd:restriction>
</xsd:simpleType>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='Child1' minOccurs='1' maxOccurs='1'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='GrandChild1' type='GCType'/>
<xsd:element name='GrandChild2' type='GCType'/>
<xsd:element name='GrandChild3' type='GCType'/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Dim schemas As XmlSchemaSet = New XmlSchemaSet()
schemas.Add("", xsdMarkup.CreateReader)
Dim doc1 As XDocument = _
<?xml version='1.0'?>
<Root>
<Child1>
<GrandChild1>AAA</GrandChild1>
<GrandChild2>ZZZ</GrandChild2>
<GrandChild3>ZZZ</GrandChild3>
</Child1>
</Root>
Console.WriteLine("Validating doc1 ...")
errors = False
doc1.Validate(schemas, AddressOf XSDErrors, True)
Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))
DumpInvalidNodes(doc1.Root)
End Sub
Cet exemple produit la sortie suivante :
Validating doc1 ...
The 'GrandChild2' element is invalid - The value 'ZZZ' is invalid according to its datatype 'GCType' - The Enumeration constraint failed.
The 'GrandChild3' element is invalid - The value 'ZZZ' is invalid according to its datatype 'GCType' - The Enumeration constraint failed.
doc1 did not validate
Invalid Element /Root
Invalid Element /Root/Child1
Invalid Element /Root/Child1/GrandChild2
Invalid Element /Root/Child1/GrandChild3
Remarques
Cette méthode d’extension valide que le XDocument modèle de contenu de schéma est conforme dans XmlSchemaSet.
Si addSchemaInfo c’est truele cas, cette méthode remplit l’arborescence XML avec l’ensemble d’informations de post-validation de schéma (PSVI).
Il existe deux étapes pour remplir l’arborescence XML avec psVI.
Tout d’abord, une annotation est ajoutée à tous les nœuds de l’arborescence pour vous permettre d’appeler Extensions.GetSchemaInfo ou Extensions.GetSchemaInfo sur un élément ou un attribut dans l’arborescence.
Deuxièmement, les éléments et attributs par défaut définis dans le XSD sont ajoutés à l’arborescence XML. En appelant l’une des GetSchemaInfo méthodes, vous pouvez déterminer si un élément ou un attribut spécifique a été ajouté à partir du XSD en tant qu’élément ou attribut par défaut.
S’applique à
Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
Cette méthode valide qu’une XElement sous-arborescence est conforme à un objet spécifié XmlSchemaObject et un XmlSchemaSet.
public:
[System::Runtime::CompilerServices::Extension]
static void Validate(System::Xml::Linq::XElement ^ source, System::Xml::Schema::XmlSchemaObject ^ partialValidationType, System::Xml::Schema::XmlSchemaSet ^ schemas, System::Xml::Schema::ValidationEventHandler ^ validationEventHandler);
public static void Validate(this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler);
public static void Validate(this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler);
static member Validate : System.Xml.Linq.XElement * System.Xml.Schema.XmlSchemaObject * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler -> unit
<Extension()>
Public Sub Validate (source As XElement, partialValidationType As XmlSchemaObject, schemas As XmlSchemaSet, validationEventHandler As ValidationEventHandler)
Paramètres
- partialValidationType
- XmlSchemaObject
Qui XmlSchemaObject spécifie la sous-arborescence à valider.
- schemas
- XmlSchemaSet
À XmlSchemaSet valider.
- validationEventHandler
- ValidationEventHandler
Pour ValidationEventHandler un événement qui se produit lorsque le lecteur rencontre des erreurs de validation. Si null, lève une exception lors d’erreurs de validation.
Exceptions
Levée pour les erreurs de validation XSD (XML Schema Definition Language).
Exemples
string xsdMarkup =
@"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='Child1' minOccurs='1' maxOccurs='1'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='GrandChild1' minOccurs='1' maxOccurs='1'/>
<xsd:element name='GrandChild2' minOccurs='1' maxOccurs='2'/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>";
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));
XDocument doc1 = new XDocument(
new XElement("Root",
new XElement("Child1",
new XElement("GrandChild1", "gc"),
new XElement("GrandChild2", "gc")
)
)
);
Console.WriteLine("Validating doc1 ...");
bool errors = false;
doc1.Validate(schemas, (sender, e) =>
{
Console.WriteLine(e.Message);
errors = true;
}, true);
Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");
Console.WriteLine();
Console.WriteLine("Validating Child1 after first edit ...");
XElement child1 = doc1.Element("Root").Element("Child1");
child1.Add(new XElement("GrandChild2", "gc"));
errors = false;
child1.Validate(child1.GetSchemaInfo().SchemaElement, schemas, (sender, e) =>
{
Console.WriteLine(e.Message);
errors = true;
});
Console.WriteLine("child1 {0}", errors ? "did not validate" : "validated");
// the following makes the Child1 element invalid according to the schema
child1.Add(new XElement("GrandChild3", "gc"));
Console.WriteLine();
Console.WriteLine("Validating Child1 after second edit ...");
child1.Validate(child1.GetSchemaInfo().SchemaElement, schemas, (sender, e) =>
{
Console.WriteLine(e.Message);
errors = true;
});
Console.WriteLine("child1 {0}", errors ? "did not validate" : "validated");
Dim errors As Boolean = False
Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)
Console.WriteLine("{0}", e.Message)
errors = True
End Sub
Sub Main()
Dim xsdMarkup As XDocument = _
<?xml version='1.0'?>
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='Child1' minOccurs='1' maxOccurs='1'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='GrandChild1' minOccurs='1' maxOccurs='1'/>
<xsd:element name='GrandChild2' minOccurs='1' maxOccurs='2'/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Dim schemas As XmlSchemaSet = New XmlSchemaSet()
schemas.Add("", xsdMarkup.CreateReader)
Dim doc1 As XDocument = _
<?xml version='1.0'?>
<Root>
<Child1>
<GrandChild1>gc</GrandChild1>
<GrandChild2>gc</GrandChild2>
</Child1>
</Root>
Console.WriteLine("Validating doc1 ...")
errors = False
doc1.Validate(schemas, AddressOf XSDErrors, True)
Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))
Console.WriteLine()
Console.WriteLine("Validating Child1 after first edit ...")
Dim child1 As XElement = doc1.Element("Root").Element("Child1")
child1.Add(<GrandChild2>gc</GrandChild2>)
errors = False
child1.Validate(child1.GetSchemaInfo().SchemaElement, schemas, AddressOf XSDErrors)
Console.WriteLine("child1 {0}", IIf(errors, "did not validate", "validated"))
' the following makes the Child1 element invalid according to the schema
child1.Add(<GrandChild3>gc</GrandChild3>)
Console.WriteLine()
Console.WriteLine("Validating Child1 after second edit ...")
child1.Validate(child1.GetSchemaInfo().SchemaElement, schemas, AddressOf XSDErrors)
Console.WriteLine("child1 {0}", IIf(errors, "did not validate", "validated"))
End Sub
Cet exemple produit la sortie suivante :
Validating doc1 ...
doc1 validated
Validating Child1 after first edit ...
child1 validated
Validating Child1 after second edit ...
The element 'Child1' has invalid child element 'GrandChild3'.
child1 did not validate
Remarques
Vous pouvez utiliser cette méthode pour vérifier qu’une sous-arborescence (avec une XElement racine) est conforme à un schéma. Vous utilisez généralement cette méthode lorsque vous avez modifié une sous-arborescence et que vous souhaitez vous assurer qu’elle est toujours conforme à son schéma. Vous pouvez valider l’intégralité du document, mais il faut moins de temps de traitement pour valider une seule sous-arborescence.
Si vous passez nullvalidationEventHandler, cette méthode déclenche une exception lors des erreurs de validation. Les avertissements de validation ne déclenchent pas d’exception.
Pour valider une sous-arborescence, vous utilisez une instance de XmlSchemaObject. Vous pouvez obtenir cette instance de différentes façons. Un moyen simple est le suivant :
Vérifiez qu’un document est conforme à un schéma.
Ajoutez l’ensemble d’informations post-validation de schéma (PSVI) en appelant la méthode d’extension Validate .
Appelez la méthode d’extension GetSchemaInfo pour récupérer un objet qui implémente IXmlSchemaInfo. À partir de l’objet récupéré, vous pouvez obtenir un XmlSchemaObject.
Si vous obtenez un XmlSchemaObject pour un XElement, le type sera XmlSchemaElement.
Si vous obtenez un XmlSchemaObject pour un XAttribute, le type sera XmlSchemaAttribute.
Une fois que vous avez une instance d’un XmlSchemaObject, vous pouvez utiliser cette méthode pour valider une sous-arborescence.
S’applique à
Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler, Boolean)
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
Valide qu’un XAttribute élément est conforme à un ensemble d’informations spécifié XmlSchemaObject et à un XmlSchemaSet, éventuellement en remplit l’arborescence XML avec l’ensemble d’informations post-validation de schéma (PSVI).
public:
[System::Runtime::CompilerServices::Extension]
static void Validate(System::Xml::Linq::XAttribute ^ source, System::Xml::Schema::XmlSchemaObject ^ partialValidationType, System::Xml::Schema::XmlSchemaSet ^ schemas, System::Xml::Schema::ValidationEventHandler ^ validationEventHandler, bool addSchemaInfo);
public static void Validate(this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler, bool addSchemaInfo);
public static void Validate(this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo);
static member Validate : System.Xml.Linq.XAttribute * System.Xml.Schema.XmlSchemaObject * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler * bool -> unit
<Extension()>
Public Sub Validate (source As XAttribute, partialValidationType As XmlSchemaObject, schemas As XmlSchemaSet, validationEventHandler As ValidationEventHandler, addSchemaInfo As Boolean)
Paramètres
- source
- XAttribute
XAttribute À valider.
- partialValidationType
- XmlSchemaObject
Qui XmlSchemaObject spécifie la sous-arborescence à valider.
- schemas
- XmlSchemaSet
À XmlSchemaSet valider.
- validationEventHandler
- ValidationEventHandler
Pour ValidationEventHandler un événement qui se produit lorsque le lecteur rencontre des erreurs de validation. Si null, lève une exception lors d’erreurs de validation.
- addSchemaInfo
- Boolean
Indiquant Boolean s’il faut remplir l’ensemble d’informations post-validation de schéma (PSVI).
Exceptions
Levée pour les erreurs de validation XSD (XML Schema Definition Language).
Exemples
static void DumpInvalidNodes(XElement el)
{
if (el.GetSchemaInfo().Validity != XmlSchemaValidity.Valid)
Console.WriteLine("Invalid Element {0}",
el.AncestorsAndSelf()
.InDocumentOrder()
.Aggregate("", (s, i) => s + "/" + i.Name.ToString()));
foreach (XAttribute att in el.Attributes())
if (att.GetSchemaInfo().Validity != XmlSchemaValidity.Valid)
Console.WriteLine("Invalid Attribute {0}",
att
.Parent
.AncestorsAndSelf()
.InDocumentOrder()
.Aggregate("",
(s, i) => s + "/" + i.Name.ToString()) + "/@" + att.Name.ToString()
);
foreach (XElement child in el.Elements())
DumpInvalidNodes(child);
}
static void Main(string[] args)
{
string xsdMarkup =
@"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base='xsd:string'>
<xsd:attribute name='Lang' use='required'>
<xsd:simpleType>
<xsd:restriction base='xsd:token'>
<xsd:enumeration value='C#'/>
<xsd:enumeration value='VB'/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
</xsd:schema>";
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));
XDocument doc1 = new XDocument(
new XElement("Root",
new XAttribute("Lang", "C#")
)
);
Console.WriteLine("Validating doc1 ...");
bool errors = false;
doc1.Validate(schemas, (sender, e) =>
{
Console.WriteLine(e.Message);
errors = true;
}, true);
Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");
DumpInvalidNodes(doc1.Root);
Console.WriteLine();
Console.WriteLine("Validating Lang attribute ...");
XAttribute lang = doc1.Element("Root").Attribute("Lang");
errors = false;
lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, (sender, e) =>
{
Console.WriteLine(e.Message);
errors = true;
}, true);
Console.WriteLine("lang {0}", errors ? "did not validate" : "validated");
DumpInvalidNodes(doc1.Root);
// the following makes the Lang attribute invalid according to the schema
lang.Value = "VC";
Console.WriteLine();
Console.WriteLine("Validating Lang attribute ...");
errors = false;
lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, (sender, e) =>
{
Console.WriteLine(e.Message);
errors = true;
}, true);
Console.WriteLine("lang {0}", errors ? "did not validate" : "validated");
DumpInvalidNodes(doc1.Root);
}
Private Sub DumpInvalidNodes(ByVal el As XElement)
If el.GetSchemaInfo.Validity <> XmlSchemaValidity.Valid Then
Console.WriteLine("Invalid Element {0}", _
el _
.AncestorsAndSelf _
.InDocumentOrder() _
.Aggregate("", _
Function(ByVal s, ByVal i) s + "/" + i.Name.ToString()))
End If
For Each att As XAttribute In el.Attributes()
If att.GetSchemaInfo.Validity <> XmlSchemaValidity.Valid Then
Console.WriteLine("Invalid Attribute {0}", _
att _
.Parent _
.AncestorsAndSelf() _
.InDocumentOrder() _
.Aggregate("", _
Function(ByVal s, ByVal i) s + "/" + i.Name.ToString()) + _
"/@" + att.Name.ToString())
End If
Next
For Each child As XElement In el.Elements()
DumpInvalidNodes(child)
Next
End Sub
Dim errors As Boolean = False
Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)
Console.WriteLine("{0}", e.Message)
errors = True
End Sub
Sub Main()
Dim xsdMarkup As XDocument = _
<?xml version='1.0'?>
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base='xsd:string'>
<xsd:attribute name='Lang' use='required'>
<xsd:simpleType>
<xsd:restriction base='xsd:token'>
<xsd:enumeration value='C#'/>
<xsd:enumeration value='VB'/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Dim schemas As XmlSchemaSet = New XmlSchemaSet()
schemas.Add("", xsdMarkup.CreateReader)
Dim doc1 As XDocument = <?xml version='1.0'?>
<Root Lang='C#'/>
Console.WriteLine("Validating doc1 ...")
errors = False
doc1.Validate(schemas, AddressOf XSDErrors, True)
Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))
DumpInvalidNodes(doc1.Root)
Console.WriteLine()
Console.WriteLine("Validating Lang attribute ...")
Dim lang As XAttribute = doc1.Element("Root").Attribute("Lang")
errors = False
lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, AddressOf XSDErrors, True)
Console.WriteLine("lang {0}", IIf(errors, "did not validate", "validated"))
DumpInvalidNodes(doc1.Root)
' the following makes the Lang attribute invalid according to the schema
lang.Value = "VC"
Console.WriteLine()
Console.WriteLine("Validating Lang attribute ...")
errors = False
lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, AddressOf XSDErrors, True)
Console.WriteLine("lang {0}", IIf(errors, "did not validate", "validated"))
DumpInvalidNodes(doc1.Root)
End Sub
Cet exemple produit la sortie suivante :
Validating doc1 ...
doc1 validated
Validating Lang attribute ...
lang validated
Validating Lang attribute ...
The 'Lang' attribute is invalid - The value 'VC' is invalid according to its datatype 'Token' - The Enumeration constraint failed.
lang did not validate
Invalid Attribute /Root/@Lang
Remarques
Vous pouvez utiliser cette méthode pour vérifier qu’un XAttribute schéma est conforme à un schéma. Vous utilisez généralement cette méthode lorsque vous avez modifié un attribut et que vous souhaitez vous assurer qu’il est toujours conforme à son schéma. Vous pouvez valider l’intégralité du document, mais il faut moins de temps de traitement pour valider uniquement l’attribut.
Si addSchemaInfo c’est truele cas, cette méthode remplit l’attribut avec l’ensemble d’informations post-validation de schéma (PSVI). Une fois que vous avez rempli l’arborescence XML avec psVI, vous pouvez appeler Extensions.GetSchemaInfo l’attribut validé. Cela est utile si vous écrivez du code qui s’appuie sur les données retournées par GetSchemaInfo.
Si vous passez nullvalidationEventHandler, cette méthode déclenche une exception lors des erreurs de validation. Les avertissements de validation ne déclenchent pas d’exception.
Pour valider un attribut, vous utilisez une instance de XmlSchemaObject. Vous pouvez obtenir cette instance de différentes façons. Un moyen simple est le suivant :
Vérifiez qu’un document est conforme à un schéma.
Ajoutez l’ensemble d’informations post-validation de schéma (PSVI) en appelant la méthode d’extension Validate .
Appelez la méthode d’extension GetSchemaInfo pour récupérer un objet qui implémente IXmlSchemaInfo. À partir de l’objet récupéré, vous pouvez obtenir un XmlSchemaObject.
Si vous obtenez un XmlSchemaObject pour un XElement, le type sera XmlSchemaElement.
Si vous obtenez un XmlSchemaObject pour un XAttribute, le type sera XmlSchemaAttribute.
Une fois que vous avez une instance d’un XmlSchemaObject, vous pouvez utiliser cette méthode pour valider un attribut.
S’applique à
Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler, Boolean)
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
- Source:
- XNodeValidator.cs
Valide qu’une XElement sous-arborescence est conforme à un objet spécifié XmlSchemaObject et à une XmlSchemaSetarborescence XML , éventuellement en remplit l’arborescence XML avec l’ensemble d’informations post-validation de schéma (PSVI).
public:
[System::Runtime::CompilerServices::Extension]
static void Validate(System::Xml::Linq::XElement ^ source, System::Xml::Schema::XmlSchemaObject ^ partialValidationType, System::Xml::Schema::XmlSchemaSet ^ schemas, System::Xml::Schema::ValidationEventHandler ^ validationEventHandler, bool addSchemaInfo);
public static void Validate(this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler, bool addSchemaInfo);
public static void Validate(this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo);
static member Validate : System.Xml.Linq.XElement * System.Xml.Schema.XmlSchemaObject * System.Xml.Schema.XmlSchemaSet * System.Xml.Schema.ValidationEventHandler * bool -> unit
<Extension()>
Public Sub Validate (source As XElement, partialValidationType As XmlSchemaObject, schemas As XmlSchemaSet, validationEventHandler As ValidationEventHandler, addSchemaInfo As Boolean)
Paramètres
- partialValidationType
- XmlSchemaObject
Qui XmlSchemaObject spécifie la sous-arborescence à valider.
- schemas
- XmlSchemaSet
À XmlSchemaSet valider.
- validationEventHandler
- ValidationEventHandler
Pour ValidationEventHandler un événement qui se produit lorsque le lecteur rencontre des erreurs de validation. Si null, lève une exception lors d’erreurs de validation.
- addSchemaInfo
- Boolean
Indiquant Boolean s’il faut remplir l’ensemble d’informations post-validation de schéma (PSVI).
Exceptions
Levée pour les erreurs de validation XSD (XML Schema Definition Language).
Exemples
string xsdMarkup =
@"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='Child1' minOccurs='1' maxOccurs='1'/>
<xsd:element name='Child2' minOccurs='1' maxOccurs='1'>
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base='xsd:string'>
<xsd:attribute name='Att1' default='Att1 Default Value'/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>";
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));
XDocument doc1 = new XDocument(
new XElement("Root",
new XElement("Child1", "c1"),
new XElement("Child2", "c2")
)
);
XDocument doc2 = new XDocument(
new XElement("Root",
new XElement("Child1", "content1"),
new XElement("Child3", "content1")
)
);
Console.WriteLine("Validating doc1");
bool errors = false;
doc1.Validate(schemas, (o, e) =>
{
Console.WriteLine("{0}", e.Message);
errors = true;
}, true);
Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");
Console.WriteLine();
Console.WriteLine("Validating doc2");
errors = false;
doc2.Validate(schemas, (o, e) =>
{
Console.WriteLine("{0}", e.Message);
errors = true;
}, true);
Console.WriteLine("doc2 {0}", errors ? "did not validate" : "validated");
Console.WriteLine();
Console.WriteLine("Contents of doc1:");
Console.WriteLine(doc1);
Console.WriteLine();
Console.WriteLine("Contents of doc2:");
Console.WriteLine(doc2);
Dim errors As Boolean = False
Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)
Console.WriteLine("{0}", e.Message)
errors = True
End Sub
Sub Main()
Dim xsdMarkup As XDocument = _
<?xml version='1.0'?>
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='Child1' minOccurs='1' maxOccurs='1'/>
<xsd:element name='Child2' minOccurs='1' maxOccurs='1'>
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base='xsd:string'>
<xsd:attribute name='Att1' default='Att1 Default Value'/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Dim schemas As XmlSchemaSet = New XmlSchemaSet()
schemas.Add("", xsdMarkup.CreateReader)
Dim doc1 As XDocument = _
<?xml version='1.0'?>
<Root>
<Child1>c1</Child1>
<Child2>c2</Child2>
</Root>
Dim doc2 As XDocument = _
<?xml version='1.0'?>
<Root>
<Child1>content1</Child1>
<Child3>content1</Child3>
</Root>
Console.WriteLine("Validating doc1")
errors = False
doc1.Validate(schemas, AddressOf XSDErrors, True)
Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))
Console.WriteLine()
Console.WriteLine("Validating doc2")
errors = False
doc2.Validate(schemas, AddressOf XSDErrors, True)
Console.WriteLine("doc2 {0}", IIf(errors, "did not validate", "validated"))
Console.WriteLine()
Console.WriteLine("Contents of doc1:")
Console.WriteLine(doc1)
Console.WriteLine()
Console.WriteLine("Contents of doc2:")
Console.WriteLine(doc2)
End Sub
Cet exemple produit la sortie suivante :
Validating doc1
doc1 validated
Validating doc2
The element 'Root' has invalid child element 'Child3'. List of possible elements expected: 'Child2'.
doc2 did not validate
Contents of doc1:
<Root>
<Child1>c1</Child1>
<Child2 Att1="Att1 Default Value">c2</Child2>
</Root>
Contents of doc2:
<Root>
<Child1>content1</Child1>
<Child3>content1</Child3>
</Root>
Remarques
Vous pouvez utiliser cette méthode pour valider qu’une sous-arborescence (avec une XElement racine de sous-arborescence) est conforme à un schéma. Vous utilisez généralement cette méthode lorsque vous avez modifié une sous-arborescence et que vous souhaitez vous assurer qu’elle est toujours conforme à son schéma. Vous pouvez valider l’intégralité du document, mais il faut moins de temps de traitement pour valider une seule sous-arborescence.
Si addSchemaInfo c’est truele cas, cette méthode remplit l’arborescence XML avec l’ensemble d’informations post-validation de schéma (PSVI).
Il existe deux aspects de remplir l’arborescence XML avec psVI.
Tout d’abord, une annotation est ajoutée à tous les nœuds de l’arborescence afin que vous puissiez maintenant appeler GetSchemaInfo un élément ou un attribut dans l’arborescence.
Deuxièmement, les éléments et attributs par défaut définis dans le XSD sont ajoutés à l’arborescence XML. En appelant l’une des GetSchemaInfo méthodes, vous pouvez déterminer si un élément ou un attribut spécifique a été ajouté à partir du XSD en tant qu’élément ou attribut par défaut.
Si vous passez nullvalidationEventHandler, cette méthode déclenche une exception lors des erreurs de validation. Les avertissements de validation ne déclenchent pas d’exception.
Pour valider une sous-arborescence, vous utilisez une instance de XmlSchemaObject. Vous pouvez obtenir cette instance de différentes façons. Un moyen simple est le suivant :
Vérifiez qu’un document est conforme à un schéma.
Ajoutez l’ensemble d’informations post-validation de schéma (PSVI) en appelant la méthode d’extension Validate .
Appelez la méthode d’extension GetSchemaInfo pour récupérer un objet qui implémente IXmlSchemaInfo. À partir de l’objet récupéré, vous pouvez obtenir un XmlSchemaObject.
Si vous obtenez un XmlSchemaObject pour un XElement, le type sera XmlSchemaElement.
Si vous obtenez un XmlSchemaObject pour un XAttribute, le type sera XmlSchemaAttribute.
Une fois que vous avez une instance d’un XmlSchemaObject, vous pouvez utiliser cette méthode pour valider une sous-arborescence..