[英]C# validate XML against generated Xsd generated class
在我們的項目中,我們具有從XSD生成的類。 當前,我們正在通過XSD文件路徑針對XSD驗證XML。
有多個XSD,我們通過存儲在數據庫中的數字選擇正確的XSD,如下所示:
“ C:/ Projects / XSD / Reports / Report_ 1.7 .xsd”
“ C:/ Projects / XSD / Reports / Report_ 1.8 .xsd”
因為當它在這樣的項目中開始具有文件路徑時,我有點緊張。 此用例是否有最佳實踐? 直接針對生成的C#類驗證xml之類的東西。 我當前的代碼:
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;
}
我建議您將XSD數據直接存儲在數據庫中,而不是僅將路徑存儲在數據庫中,您非常正確的認為這是一個壞主意。
例如,您可以將XSD數據存儲為類似MS SQL Server中的NVarChar數據類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.