In unserem Projekt haben wir Klassen aus XSD generiert. Zurzeit validieren wir den XML-Code anhand des XSD-Dateipfads gegen den XSD.C# validate XML gegen generierte Xsd generierte Klasse
Es gibt mehrere XSD ist und wir wählen die richtige durch eine Zahl in der Datenbank gespeichert sind gerade wie:
"C:/Projekte/XSD/Berichte/Report_ 1.7 .xsd"
" C:/Projekte/XSD/Berichte/Report_ 1.8 XSD“
Weil ich ein wenig nervös geworden, wenn es beginnt, wie diese Dateipfade in einem Projekt zu haben. Gibt es eine Best Practice für diesen Anwendungsfall? So etwas wie die Validierung des XML gegen die generierte C# -Klasse direkt. Mein aktueller Code:
private static string GetXsdPath(SchemaType aSchemaType, string aTransferRevision)
{
var lFileBeginnName = XsdStrategies.XsdService.GetXsdName(aSchemaType);
var lDirectoryName = XsdStrategies.XsdService.GetDirectoryName(aSchemaType);
string lRoot = HttpContext.Current.Server.MapPath("~");
string lFullRootPath = Path.GetFullPath(Path.Combine(lRoot, @"../"));
return string.Format(
CultureInfo.CurrentCulture, @"{0}/Reports/{1}/Report_V{2}.xsd",
lFullRootPath,
lDirectoryName,
aTransferRevision);
}
public bool IsValidXml(string aXmlContent, string aXsdFilePath, XNamespace aNamespaceName)
{
try
{
if (aNamespaceName == null)
{
this.Logger.AddLogEntry(LogLevel.Error, "Namespace is null.");
return false;
}
var lXdoc = XDocument.Parse(aXmlContent);
var lSchemas = new XmlSchemaSet();
lSchemas.Add(aNamespaceName.NamespaceName, aXsdFilePath);
// xDoc Validate throws an excption if xml not conforms xsd.
lXdoc.Validate(lSchemas, null);
}
catch (XmlSchemaValidationException lEx)
{
this.Logger.AddLogEntry(LogLevel.Error, $"The Xml is not valid against the Xsd: {lEx}");
return false;
}
catch (XmlSchemaException lEx)
{
this.Logger.AddLogEntry(LogLevel.Error, $"Therse is something wrong in the Schema-Version from Xml and Xsd: {lEx}");
return false;
}
catch (XmlException lEx)
{
this.Logger.AddLogEntry(LogLevel.Error, $"A generic Error occured durring Xml against Xsd validation: {lEx}");
return false;
}
return true;
}