Validating XML with an XmlReader against an XML Schema (VB)
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
Untitled Page
File: Default.aspx.vb
Imports System.IO
Imports System.Xml
Imports System.Xml.Schema
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
Dim bookcount As Integer = 0
Dim settings As New XmlReaderSettings()
Dim booksSchemaFile As String = Path.Combine(Request.PhysicalApplicationPath, "Data.xsd")
settings.Schemas.Add(Nothing, XmlReader.Create(booksSchemaFile))
settings.ValidationType = ValidationType.Schema
settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings
AddHandler settings.ValidationEventHandler, _
AddressOf settings_ValidationEventHandler
settings.IgnoreWhitespace = True
settings.IgnoreComments = True
Dim booksFile As String = Path.Combine(Request.PhysicalApplicationPath, "Data.xml")
Using reader As XmlReader = XmlReader.Create(booksFile, settings)
While (reader.Read())
If (reader.NodeType = XmlNodeType.Element And "book" = reader.LocalName) Then
bookcount += 1
End If
End While
End Using
Response.Write(String.Format("Found {0} books!", bookcount))
End Sub
Sub settings_ValidationEventHandler(ByVal sender As Object, _
ByVal e As System.Xml.Schema.ValidationEventArgs)
Response.Write(e.Message)
End Sub
End Class
File: Data.xml
title 1
A
B
8
title 2
C
D
11.99
File: Data.xsd