Validating an Xml Against Referenced Xsd in C#

Validating an XML against referenced XSD in C#

You need to create an XmlReaderSettings instance and pass that to your XmlReader when you create it. Then you can subscribe to the ValidationEventHandler in the settings to receive validation errors. Your code will end up looking like this:

using System.Xml;
using System.Xml.Schema;
using System.IO;

public class ValidXSD
{
public static void Main()
{

// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

// Create the XmlReader object.
XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);

// Parse the file.
while (reader.Read()) ;

}
// Display any warnings or errors.
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
Console.WriteLine("\tWarning: Matching schema not found. No validation occurred." + args.Message);
else
Console.WriteLine("\tValidation error: " + args.Message);

}
}

Validating xml against an xsd that has include and import in c#

I created a XmlReaderSettings with following options:

XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = new XmlXsdResolver(); // Need this for resolving include and import
settings.ValidationType = ValidationType.Schema; // This might not be needed, I am using same settings to validate the input xml
settings.DtdProcessing = DtdProcessing.Parse; // I have an include that is dtd. maybe I should prohibit dtd after I compile the xsd files.

Then I used it with an XmlReader to read the xsd. The important part is that I had to put a basePath so that the XmlXsdResolve can find other xsd files.

using (XmlReader xsd = XmlReader.Create(new FileStream(xsdPath, FileMode.Open, FileAccess.Read), settings, basePath))
{
settings.Schemas.Add(null, xsd);
}

settings.Schemas.Compile();

This is the XmlXsdResolver to find included and imported xsd files:

protected class XmlXsdResolver : XmlUrlResolver
{
public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
{
return base.GetEntity(absoluteUri, role, ofObjectToReturn);
}
}

C# validating a XML with a XSD

This does what you're looking for, good luck.

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;

namespace xmlutil {
class Program {
static void Main(string[] args) {

string strFileName = String.Empty;

try {

if (args.Length < 2) {
throw new Exception("Usage: xmlutil.exe [file.xml|folder\\*.xml] file.xsd");
}

System.IO.FileAttributes attr = System.IO.File.GetAttributes( args[0] );

XmlReaderSettings settings = new XmlReaderSettings();

strFileName = args[1]; // to detect errors in the schema

settings.Schemas.Add(null, args[1]);
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags =
XmlSchemaValidationFlags.ReportValidationWarnings |
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ProcessInlineSchema |
XmlSchemaValidationFlags.ProcessSchemaLocation;


if (attr.HasFlag(System.IO.FileAttributes.Directory)) {

string[] directories = Directory.GetDirectories(args[0]);




string[] files = Directory.GetFiles(args[0], "*.xml", SearchOption.AllDirectories);
int i = files.Length;
Console.WriteLine("Processing folder " + args[0] + " - " + i + " files.");

int nTen = Convert.ToInt32(files.Length / 10);
int nCount = 0;

for (i = 0; i < files.Length; i++) {
strFileName = files[i];
try {
ValidateFile(files[i], settings);

if ((i % nTen) == 0) {
if (nCount > 0) {
Console.WriteLine(nCount * 10 + "% complete.");
}
nCount++;
}
} catch (Exception ex2) {
Console.Error.WriteLine(strFileName);
Console.Error.WriteLine(ex2.Message);
}
}
} else {
strFileName = args[0];
ValidateFile(args[0], settings);
}
} catch (XmlSchemaException exs) {
Console.Error.WriteLine(strFileName + " schema validation exeption" );
Console.Error.WriteLine(exs.Message + " Line: " + exs.LineNumber + " Column: " + exs.LinePosition );
} catch (Exception ex) {
Console.Error.WriteLine(strFileName);
Console.Error.WriteLine(ex.Message);
}

}

static void ValidateFile(string strXMLFile, XmlReaderSettings settings) {

XmlDocument document = new XmlDocument();
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

XmlReader reader = XmlReader.Create(strXMLFile, settings);
document.Load(reader);
// the following call to Validate succeeds.
document.Validate(eventHandler);
}

static void ValidationEventHandler(object sender, ValidationEventArgs e) {
switch (e.Severity) {
case XmlSeverityType.Error:
Console.WriteLine("Error: {0}", e.Message);
break;
case XmlSeverityType.Warning:
Console.WriteLine("Warning {0}", e.Message);
break;
}

}
}
}

validate xml with XSD file in C#

I create and used this simple code to create one console program and valid all xml in my test process

class Program {
static void Main(string[] args) {
Console.WriteLine("validando input.xml con input.xsd");
var schemas = new XmlSchemaSet();
schemas.Add("", "input.xsd");
Console.WriteLine("Validando...");
var custOrdDoc = XDocument.Load("input.xml");
var errors = false;
custOrdDoc.Validate(schemas, (o, e) => {
Console.WriteLine("{0}", e.Message);
errors = true;
});
Console.WriteLine("archivo {0}", errors ? "No cumple con la validacion" : "validacion exitosa");
Console.ReadKey();
}
}

Validating an XML against an embedded XSD in C#

Try this:

Stream objStream = objFile.PostedFile.InputStream;

// Open XML file
XmlTextReader xtrFile = new XmlTextReader(objStream);

// Create validator
XmlValidatingReader xvrValidator = new XmlValidatingReader(xtrFile);
xvrValidator.ValidationType = ValidationType.Schema;

// Add XSD to validator
XmlSchemaCollection xscSchema = new XmlSchemaCollection();
xscSchema.Add("xxxxx", Server.MapPath(@"/zzz/XSD/yyyyy.xsd"));
xvrValidator.Schemas.Add(xscSchema);

try
{
while (xvrValidator.Read())
{
}
}
catch (Exception ex)
{
// Error on validation
}

Validating an XML against referenced XSD in C#

You need to create an XmlReaderSettings instance and pass that to your XmlReader when you create it. Then you can subscribe to the ValidationEventHandler in the settings to receive validation errors. Your code will end up looking like this:

using System.Xml;
using System.Xml.Schema;
using System.IO;

public class ValidXSD
{
public static void Main()
{

// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

// Create the XmlReader object.
XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);

// Parse the file.
while (reader.Read()) ;

}
// Display any warnings or errors.
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
Console.WriteLine("\tWarning: Matching schema not found. No validation occurred." + args.Message);
else
Console.WriteLine("\tValidation error: " + args.Message);

}
}

C# Validate simple XML against XSD does not work when using a prefix

First off your schema has no targetnamespace, if you change that then it mostly works, i.e.

<?xml version="1.0" encoding="utf-8" ?>
<!--Created with Liquid XML 2017 Liquid Studio - Data Designer Edition 15.0.0.6978 (https://www.liquid-technologies.com)-->
<xs:schema xmlns="urn.mota:ndd.acu.gisae.VicuSolution111"
elementFormDefault="qualified"
targetNamespace="urn.mota:ndd.acu.gisae.VicuSolution111"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="VicuSolution111">
<xs:complexType>
<xs:sequence>
<xs:element name="Header" minOccurs="0" maxOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="TransactionType" minOccurs="1" maxOccurs="1">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="40" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

But then your XML is wrong, if you modify it like this it would work

<?xml version="1.0" encoding="utf-8" ?>
<ns0:VicuSolution111 xmlns:ns0="urn.mota:ndd.acu.gisae.VicuSolution111">
<ns0:Header>
<ns0:TransactionType></ns0:TransactionType>
</ns0:Header>
</ns0:VicuSolution111>

If your original XML was the output you wanted then you need to break your schema into 2 files, one containing VicuSolution111 with no targetnamespace the other containing Header with the targetnamespace set to 'urn.mota:ndd.acu.gisae.VicuSolution111'.

Incidently, the reason the parser could not find a schema definition for VicuSolution111 (which has no namespace in your xml file) is because you told the parser that the schema represents items in the namespace 'urn.mota:ndd.acu.gisae.VicuSolution111'.

    XmlSchema xs = booksSettings.Schemas.Add("urn.mota:ndd.acu.gisae.VicuSolution111", "validation.xsd");


Related Topics



Leave a reply



Submit