Donate

Validate XML against XSD File In C# And VB.NET

In my nature of work, we dealt with XML files and schema on a daily basis. And here's a cool snippet on validating XML file against and XSD file.
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;

public class Form1
{

 private void Form1_Load(SystemObject sender, SystemEventArgs e)
 {
  XmlDocument myDocument = new XmlDocument();
  myDocument.Load("C:\\somefile.xml");
  myDocument.Schemas.Add("namespace here or empty string", "C:\\someschema.xsd");
  ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
  myDocument.Validate(eventHandler);
 }

 private void ValidationEventHandler(object sender, ValidationEventArgs e)
 {
  switch (e.Severity) {
   case XmlSeverityType.Error:
    Debug.WriteLine("Error: {0}", e.Message);
    break;
   case XmlSeverityType.Warning:
    Debug.WriteLine("Warning {0}", e.Message);
    break;
  }
 }
}
VB.NET
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Imports System
Imports System.Xml
Imports System.Xml.Schema
Imports System.Xml.XPath
 
Public Class Form1
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim myDocument As New XmlDocument
        myDocument.Load("C:\somefile.xml")
        myDocument.Schemas.Add("namespace here or empty string", "C:\someschema.xsd")
        Dim eventHandler As ValidationEventHandler = New ValidationEventHandler(AddressOf ValidationEventHandler)
        myDocument.Validate(eventHandler)
    End Sub
 
    Private Sub ValidationEventHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)
        Select Case e.Severity
            Case XmlSeverityType.Error
                Debug.WriteLine("Error: {0}", e.Message)
            Case XmlSeverityType.Warning
                Debug.WriteLine("Warning {0}", e.Message)
        End Select
    End Sub
 
End Class

Thanks to kleinma(Visual Basic Guru) for this snippet.

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input