Re: On the Fly XML Validation
- From: Martin Honnen <mahotrash@xxxxxxxx>
- Date: Thu, 28 Feb 2008 14:04:19 +0100
Joy wrote:
My XML is in string however my XSD will be in a file.
I am using VB .NET.
Here is an example class that writes validation warning, validation errors and well-formedness exceptions to the console:
Imports System
Imports System.Xml
Imports System.Xml.Schema
Imports System.IO
Module TestValidation
Sub Main()
Dim xml As String = "<root><foo>1</foo></root>"
Dim schema As String = "..\..\XSDSchema1.xsd"
Dim validator As New ValidateXml(xml, schema)
Dim valid As Boolean = validator.Validate()
Console.WriteLine("{0} is valid: {1}.", xml, valid)
End Sub
End Module
Public Class ValidateXml
Private _valid As Boolean
Public Property Valid() As Boolean
Get
Return _valid
End Get
Set(ByVal value As Boolean)
_valid = value
End Set
End Property
Private _xml As String
Public Property Xml() As String
Get
Return _xml
End Get
Set(ByVal value As String)
_xml = value
End Set
End Property
Private _schemaFile As String
Public Property SchemaFile() As String
Get
Return _schemaFile
End Get
Set(ByVal value As String)
_schemaFile = value
End Set
End Property
Public Sub New(ByVal x As String, ByVal schema As String)
_xml = x
_schemaFile = schema
End Sub
Public Function Validate() As Boolean
_valid = True
Dim settings As New XmlReaderSettings()
settings.ValidationType = ValidationType.Schema
settings.ValidationFlags = settings.ValidationFlags Or XmlSchemaValidationFlags.ReportValidationWarnings
AddHandler settings.ValidationEventHandler, AddressOf ValidationHandler
settings.Schemas.Add(Nothing, _schemaFile)
Using reader As XmlReader = XmlReader.Create(New StringReader(_xml), settings)
Try
While reader.Read()
End While
Catch ex As XmlException
Console.WriteLine("Parse error: {0}", ex.Message)
_valid = False
End Try
Return _valid
End Using
End Function
Private Sub ValidationHandler(ByVal sender As Object, ByVal vargs As ValidationEventArgs)
If vargs.Severity = XmlSeverityType.Error Then
_valid = False
End If
Console.WriteLine("{0}: {1}", vargs.Severity, vargs.Message)
End Sub
End Class
--
Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
.
- References:
- Re: On the Fly XML Validation
- From: Martin Honnen
- Re: On the Fly XML Validation
- From: Martin Honnen
- Re: On the Fly XML Validation
- Prev by Date: Re: now to set line endings with XSLT
- Next by Date: Re: now to set line endings with XSLT
- Previous by thread: Re: On the Fly XML Validation
- Next by thread: "XML Source" (108) was unable to read the XML data.
- Index(es):
Relevant Pages
|