Imports System.IO
Imports System.Xml
Imports System.Xml.Schema
Imports System.Xml.Serialization

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
           Handles Me.Load
        'Create factory early
        Dim factory As New XmlSerializerFactory

        Dim settings As New XmlReaderSettings()

        Dim nt As New NameTable()
        Dim book As Object = nt.Add("book")
        Dim price As Object = nt.Add("price")
        Dim author As Object = nt.Add("author")
        settings.NameTable = nt

        Dim booksSchemaFile As String = Path.Combine(Request.PhysicalApplicationPath, "books.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, "books.xml")
        Using reader As XmlReader = XmlReader.Create(booksFile, settings)
            While (reader.Read())
                If (reader.NodeType = XmlNodeType.Element And author.Equals(reader.LocalName)) Then

                    'Then use the factory to create and cache serializers
                    Dim xs As XmlSerializer = factory.CreateSerializer(GetType(Author))
                    Dim a As Author = CType(xs.Deserialize(reader.ReadSubtree), Author)
                    Response.Write(String.Format("Author: {1}, {0}<BR/>", _
                        a.FirstName, a.LastName))
                End If
            End While
        End Using
    End Sub

    Sub settings_ValidationEventHandler(ByVal sender As Object, _
            ByVal e As System.Xml.Schema.ValidationEventArgs)
        Response.Write(e.Message)
    End Sub

End Class
