我有一个 XML 文件,它通过正常的文件上传控件上传到 ASP.Net 页面。当它启动时,我正在尝试验证和反序列化 XML。但是,下面的代码对于验证引用它的 XSD 的 XML 文件非常方便,如下所示:
xsi:schemaLocation="someurl ..\localSchemaPath.xsd"
但是,如果我上传此 XML 文件,则仅上传 XML 文件,因此 ..\localSchemaPath.xsd 不存在,因此无法验证。
即使我将 XSD 存储在本地,它仍然不太正确,因为 XML 文件可以使用如下模式位置编写:
xsi:schemaLocation="someurl ..\localSchemaPath.xsd"
或 xsi:schemaLocation="someurl localSchemaPath.xsd" 或 xsi:schemaLocation="someurl ....\localSchemaPath.xsd" 如果它愿意。
困境!
(出于这个问题的目的,我从以下代码中提取了以下代码:Validating an XML against referenced XSD in C#)
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);
}
}