How to validate XDocument with xsd file in C# and VB.NET

To validate xml file with xsd file in C# and VB.NET you can use the following snippet.

Sample C#

public string ValidateXDocument(XDocument xmlFile, string xsdFile)
{
	try
	{
		var retVal = String.Empty;
		var schemas = new XmlSchemaSet();
		schemas.Add(null, xsdFile);
		xmlFile.Validate(schemas, (o, e) =>
		{
			retVal = e.Message;
		});
		return retVal;
	}
	catch (Exception ex)
	{
		//handle the exception your way
		return ex.ToString();
	}
}

Sample VB.NET

Public Function ValidateXDocument(xmlFile As XDocument, xsdFile As String) As String
	Try
		Dim retVal = [String].Empty
		Dim schemas = New XmlSchemaSet()
		schemas.Add(Nothing, xsdFile)
		xmlFile.Validate(schemas, Function(o, e) 
		retVal = e.Message

End Function)
		Return retVal
	Catch ex As Exception
		'handle the exception your way
		Return ex.ToString()
	End Try
End Function

Please Share us:
Please rate this snippet

One thought on “How to validate XDocument with xsd file in C# and VB.NET

Leave a Reply