Write and Validate XML with a DTD in Memory in .Net

This is the sample of piecing together a lto of different posts, so I thought I’d put a sample on the web…

I’m putting it in VB.Net (because I was writing in it due to project requirements

Imports System.Xml
Imports System.Xml.Schema
Imports System.Text
Imports System.IO

Public Class MyXMLTool
  Private sb As New StringBuilder(“”)
  Private xw As XmlWriter
  Private validXml As Boolean = True
  Private validationErrors As String = “”

  Public Sub New()
  End Sub

  Public ReadOnly Property ValidationMessages() As String Implements
   Get
     Return validationErrors
   End Get
  End Property

  Public Function Prepare() As Boolean Implements iEnroller.Prepare
    xw = XmlWriter.Create(sb)
    xw.WriteStartDocument()
    xw.WriteDocType(“MyRootElement”, Nothing, “MyDTD.dtd”, “<!– This file represents my data –>”)
    xw.WriteStartElement(“MyRootElement”)
    ‘Write everything else you want to write
    xw.WriteEndElement()

    xw.WriteEndDocument()
    xw.Close()
    Return True
  End Function

  Public Function Validate() As Boolean
     Dim xs As New XmlReaderSettings()
    xs.ProhibitDtd = False
    xs.ValidationType = ValidationType.DTD
    AddHandler xs.ValidationEventHandler, New ValidationEventHandler(AddressOf ValidationCallback)

    Dim sr As New StringReader(sb.ToString())
    Dim xr As XmlReader = XmlReader.Create(sr, xs)

    ‘this forces the validation process to occur by reading every line
    While xr.Read
    End While

    ‘this will be set False if the ValidationCallback happens
    Return validXml
  End Function

  Public Sub ValidationCallback(ByVal sender As Object, ByVal e As ValidationEventArgs)
    validXml = False
    validationErrors = e.Message
  End Sub

  Public Sub GetXML() as String
    return sb.ToString()
  End Sub
End Class