开发者

Validating XML with multiple XSD using relative paths in .NET

I'm trying to write a generic VB.NET (VS2005) function to validate an XML document against an XSD. This works fine until I use an XSD with a relative path include like:

<xs:include schemaLocation="test.02.xsd" />

It can never seem to find what is included in any secondary documents. Here is my original function below. I've been playing with XmlUrlResolver() but I cannot seem to make any progress using that either. Any help here would be greatly appreciated.

Private Sub ValidatingProcess(ByVal XSDPath As String, ByVal XMLPath As String)
    Try
   开发者_如何学编程     Me.Reader = New XmlTextReader(XMLPath)
        Dim SR As New StreamReader(XSDPath)
        Dim Schema As New XmlSchema()
        Schema = XmlSchema.Read(SR, New ValidationEventHandler(AddressOf ReaderSettings_ValidationEventHandler))
        Dim ReaderSettings As New XmlReaderSettings()
        ReaderSettings.ValidationType = ValidationType.Schema
        ReaderSettings.Schemas.Add(Schema)
        AddHandler ReaderSettings.ValidationEventHandler, AddressOf ReaderSettings_ValidationEventHandler
        Dim objXmlReader As XmlReader = XmlReader.Create(Reader, ReaderSettings)
        While objXmlReader.Read()
        End While
    Catch AccessEx As UnauthorizedAccessException
        Throw AccessEx
    Catch Ex As Exception
        Throw Ex
    End Try
End Sub


I solved it by creating a custom XmlUrlResolver like this:

Class CustomResolver
    Inherits XmlUrlResolver

    Private _CustomBaseUri As Uri

    Public Sub New(ByVal baseUri As Uri)
        If baseUri.IsFile Then
            _CustomBaseUri = New Uri(Path.GetDirectoryName(baseUri.LocalPath.ToString()) & "\")
        Else
        End If
        Me._CustomBaseUri = baseUri
    End Sub

    Public Overloads Overrides Function ResolveUri(ByVal baseUri As Uri, ByVal relativeUri As String) As Uri
        If baseUri IsNot Nothing Then
            Return MyBase.ResolveUri(baseUri, relativeUri)
        Else
            Return MyBase.ResolveUri(_CustomBaseUri, relativeUri)
        End If
    End Function
End Class
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜