Validates that an XDocument conforms to an XSD in an XmlSchemaSet
Imports System
Imports System.Xml
Imports System.Xml.XPath
Imports System.Xml.Schema
Public Class MainClass
Shared errors As Boolean = False
Private Shared Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)
Console.WriteLine("{0}", e.Message)
errors = True
End Sub
Public Shared 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>
errors = False
doc1.Validate(schemas, AddressOf XSDErrors, True)
Console.WriteLine("doc1 {0}", IIf(errors, "did not validate", "validated"))
errors = False
doc2.Validate(schemas, AddressOf XSDErrors, True)
Console.WriteLine("doc2 {0}", IIf(errors, "did not validate", "validated"))
End Sub
End Class
Related examples in the same category