Xsd et csharp

De Banane Atomic
Aller à la navigationAller à la recherche

Validation d'un fichier XML avec plusieurs fichiers XSD

Csharp.svg
var settings = new XmlReaderSettings();
settings.Schemas.Add("urn:xxx", xsdFilePath); // xmlns du noeud principal
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += xsdValidationEventHandler;

using (var reader = XmlReader.Create(xmlFilePath, settings))
{
    while (reader.Read()) { }
}

Validation d'un fichier XML avec plusieurs fichiers XSD stockés comme ressource dans une Assembly

Csharp.svg
string xmlFilePath = @"C:\Dossier\Fichier.xml";
Assembly assemblyEmbedingXsd = Assembly.LoadFile(@"C:\Dossier\Assembly.dll");
string resourceAssemblyFolder = "Namespace.Dossier";
string xsdFileName = "FichierPrincipal.xsd";

var resolver = new ResourceXmlResolver();
resolver.ResourceAssemblyFolder = resourceAssemblyFolder;
resolver.ResourceAssembly = assemblyEmbedingXsd;
            
var streamXsdFile = resolver.LoadInitialSchema(xsdFileName);
if (streamXsdFile == null)
{
    throw new NullReferenceException(
        String.Format("The ressource '{0}' is not found in the assembly '{1}' folder '{2}'", 
            xsdFileName, assemblyEmbedingXsd.FullName, resourceAssemblyFolder));
}

XmlSchema initialSchema = XmlSchema.Read(streamXsdFile, validationEventHandler);

var schemas = new XmlSchemaSet();
schemas.XmlResolver = resolver;
schemas.Add(initialSchema);

var xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.Schemas.Add(schemas);
xmlReaderSettings.ValidationType = ValidationType.Schema;
xmlReaderSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
xmlReaderSettings.ValidationEventHandler += xsdValidationEventHandler;

using (var xmlReader = XmlReader.Create(new StreamReader(xmlFilePath), xmlReaderSettings))
{
    while (xmlReader.Read()) { }
}

private void xsdValidationEventHandler(object sender, ValidationEventArgs e)
{
    if (e.Severity == XmlSeverityType.Warning)
    {

    }
    else if (e.Severity == XmlSeverityType.Error)
    {
        var message = e.Message;
        var ln = e.Exception.LineNumber;
        var lp = e.Exception.LinePosition;
    }
}