Validation of XML against XSD, and ValidationEventHandler
So the below code validates test.xml against validate.xsd (found the sample code in these forums).
Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim myDocument As New XmlDocument
Dim lsFile As String
lsFile = "C:\test.xml"
myDocument.Load(lsFile)
myDocument.Schemas.Add("", "c:\validate.xsd")
myDocument.Validate(AddressOf ValidationEventHandler)
MsgBox(myDocument.DocumentElement.ChildNodes(0).Name)
End Sub
Private Sub ValidationEventHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)
Select Case e.Severity
Case XmlSeverityType.Error
TextBox1.Text = TextBox1.Text & vbNewLine & "Error: " & e.Message
Case XmlSeverityType.Warning
TextBox1.Text = TextBox1.Text & vbNewLine & "Warning: " & e.Message
End Select
For every error it finds, ValidationEventHandler is fired off and a line describing the error is added to the text box.
My questions are
1) How do I access the XMLElement object that was found to be invalid against the XSD, inside the ValidationEventHandler?
For example test.xml has:
<File>
<Item>
<ID>1232231</ID>
<Date>xx</Date>
</Item>
...
</File>
<Date> is invalid against validate.xsd, because it was expecting a real date. So ValidationEventHandler is triggered.
Inside the ValidationEventHandler, how can I get access to that <Date> XMLElement (or whatever element that was invalid)?
I want to access <Date>'s parent node, so I can access <ID> and figure out where this error occurred.
2) Is there a way to pass parameters into ValidationEventHandler from Form1_Load? (Like say I want to pass it an Array to store all the validation errors it finds).
3) Currently exception.linenumber does not work (it returns 0). Is there a way to get the line number the error was found?
Re: Validation of XML against XSD, and ValidationEventHandler
Can you post part of your XML file, and the XSD?