I am trying to validate my xml against an xsd file. The code below works fine but the errors it reports seem to indicate there is something wrong with the reference to the xsd file. It cannot find the xsd file.
Imports System
Imports System.Collections.Generic
Imports System.Xml
Imports System.Xml.Schema
Public Class XmlValidator
''' <summary>
''' Get any error messages that were found validating the XML document against
''' an XSD schema document.
''' </summary>
Public ReadOnly Property ValidationErrors() As List(Of String)
Get
Return _validationErrors
End Get
End Property
Public Sub ValidateXmlAgainstSchema(B
yVal xmlFileName As String, ByVal xsdFileName As String)
Using xsdReader As XmlReader = XmlReader.Create(xsdFileNa
me)
' Read the schema from a file.
Dim schema As XmlSchema = XmlSchema.Read(xsdReader, AddressOf OnValidationEvent)
' Setup the XmlReader for schema validation.
Dim settings As New XmlReaderSettings()
settings.ValidationType = ValidationType.Schema
settings.ValidationFlags = XmlSchemaValidationFlags.R
eportValid
ationWarni
ngs
AddHandler settings.ValidationEventHa
ndler, AddressOf OnValidationEvent
' Add the schema document.
settings.Schemas.Add(schem
a)
' Read each element of the document. Any errors will raise a ValidationEvent.
Using reader As XmlReader = XmlReader.Create(xmlFileNa
me, settings)
While reader.Read()
End While
End Using
End Using
End Sub
Private Sub OnValidationEvent(ByVal sender As Object, ByVal e As ValidationEventArgs)
_validationErrors.Add(e.Me
ssage)
End Sub
Private _validationErrors As New List(Of String)()
End Class
Here is an XML sample
<?xml version="1.0" encoding="utf-8"?>
<RootNode>
<SubNode>
<SomeItem1>Some Item One</SomeItem1>
<SomeItem2>Some Item Two</SomeItem2>
<SomeErrorItem>This should not be here!!</SomeErrorItem>
</SubNode>
</RootNode>
and equivalent xsd file
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="TestSchema" targetNamespace="
http://tempuri.org/TestSchema.xsd" elementFormDefault="qualif
ied" xmlns="
http://tempuri.org/TestSchema.xsd" xmlns:mstns="
http://tempuri.org/TestSchema.xsd" xmlns:xs="
http://www.w3.org/2001/XMLSchema">
<xs:element name="RootNode">
<xs:complexType>
<xs:sequence>
<xs:element name="SubNode">
<xs:complexType>
<xs:sequence>
<xs:element name="SomeItem1" type="xs:string" />
<xs:element name="SomeItem2" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Can someone tell me what is wrong. What else do I have to do to validate the xml. I would expect one error back due to the extra error field added but instead i get a list of error saying it could not find xsd file for any of the xml nodes.
Cheers
Start Free Trial