I am having some trouble validating XML using the XmlValidatingReader.
I have created some xml and used the visual studio to generate the
schema. So I am confident that the xml and schema match.
The problem I am having is that the validation event fires for each
node in the xml. It seems to be completely ignoring the schema that I
have used.
I'm wondering if I need to do something extra to tell the xml which
schema to use.
Here's the code. Any help at all would be great.
Thanks
Andy
public sub Main()
Dim sSchema As String = "<?xml version='1.0'?>" & _
"<xs:schema id='MyApp'
targetNamespace='http://tempuri.org/test.xsd'
xmlns:mstns='http://tempuri.org/test.xsd'
xmlns='http://tempuri.org/test.xsd'
xmlns:xs='http://www.w3.org/2001/XMLSchema'
xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'
attributeFormDefault='qualified' elementFormDefault='qualified'>" & _
"<xs:element name='MyApp'
msdata:IsDataSet='true' msdata:Locale='en-GB'
msdata:EnforceConstraints='False'>" & _
"<xs:complexType>" & _
"<xs:choice
maxOccurs='unbounded'>" & _
"<xs:element name='os'>" &
_
"<xs:complexType>" & _
"<xs:sequence>" & _
"<xs:element
name='client' minOccurs='0' maxOccurs='unbounded'>" & _
"<xs:complexType>"
& _
"<xs:attribute
name='wmp_v' form='unqualified' type='xs:string' />" & _
"<xs:attribute
name='s_v' form='unqualified' type='xs:string' />" & _
"<xs:attribute
name='file' form='unqualified' type='xs:string' />" & _
"</xs:complexType>" & _
"</xs:element>" & _
"</xs:sequence>" & _
"<xs:attribute
name='v' form='unqualified' type='xs:string' />" & _
"</xs:complexType>" & _
"</xs:element>" & _
"</xs:choice>" & _
"</xs:complexType>" & _
"</xs:element>" & _
"</xs:schema>"
Dim ValidatorReader As New Xml.XmlTextReader(New
StringReader(sSchema))
Dim ValidationSchema As New Xml.Schema.XmlSchema
Dim colSchemas As New Xml.Schema.XmlSchemaCollection
ValidationSchema.Read(ValidatorReader, AddressOf
ValidationEventHandler)
ValidationSchema.Compile(AddressOf ValidationEventHandler)
colSchemas.Add(ValidationSchema)
'XML to validate
Dim sXML As String = "<MyApp
xmlns='http://tempuri.org/test.xsd'>" & _
"<os v='xp'> <client wmp_v='9'
s_v='9' file=''/><client wmp_v='10' s_v='10' file=''/></os>" & _
"</MyApp>"
Dim InputXMLReader As New Xml.XmlTextReader(New
StringReader(sXML))
Dim xmlValidator As New
Xml.XmlValidatingReader(InputXMLReader)
xmlValidator.ValidationType = Xml.ValidationType.Schema
AddHandler xmlValidator.ValidationEventHandler, AddressOf
ValidationEventHandler
'Add schema to the validating reader
xmlValidator.Schemas.Add(colSchemas)
While xmlValidator.Read()
'Validation even is fired for evey node.
End While
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
End Sub
Public Shared Sub ValidationEventHandler(ByVal sender As Object,
ByVal e As Xml.Schema.ValidationEventArgs)
Select Case e.Severity
Case Xml.Schema.XmlSeverityType.Error
Debug.WriteLine(e.Exception.Message)
Case Xml.Schema.XmlSeverityType.Warning
Debug.WriteLine(e.Exception.Message)
End Select
End Sub