Thursday, July 07, 2005

Chicken or Egg problem with XSD and XML

Should we create the XSD or XML first? This is similar to the Chicken or Egg problem. Its ok to create the XML file first if that is a place holder to create the XSD. But any subsequent creation of XML file should be validated against the schema. So, how can we validate the schema in .NET? Here is a code that is use to identify if the schema is valid as well as process the elements.

Private isValid As Boolean = True
Sub Main()
Dim reader As New XmlTextReader("C:\MyFolder\Example.xml")
Dim valid As New XmlValidatingReader(reader)
valid.ValidationType = ValidationType.Schema
AddHandler valid.ValidationEventHandler, AddressOf MyValidationEventHandler
Try

While valid.Read
' Do any processing here
End While

Catch ex As Exception
Console.WriteLine("There is an exception {0}", ex.InnerException)
End Try

valid.Close()

If isValid Then
Console.WriteLine(" The document is valid")
Else
Console.WriteLine(" The document is not valid ")
End If
' This is only to prevent the console window from closing.
Console.ReadLine()

End Sub

' Event handler
Public Sub MyValidationEventHandler(ByVal sender As Object, _
ByVal args As ValidationEventArgs)
isValid = False
Console.WriteLine("Validation event" & vbCrLf & args.Message)
End Sub

Make sure in the XML file you mention either of this attributes for the schema location in the root element.
xsi:noNamespaceSchemaLocation="example.xsd"
or
xsi:SchemaLocation="example.xsd"

The choice of the attribute is based on whether the XML file has namespace or not.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home