我有一个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);
}
}
答案 0 :(得分:1)
我无法确定您是否正在尝试针对任何引用架构进行通用验证,或者您是否具有每次都验证的特定架构,并且只是不确定如何处理引用
如果是后者,那么在互联网上公开架构,并告诉人们通过URI引用它。
如果是前者,那么我建议如下:
yourSchema.xsd
的引用;请在下方上传此文件”,并附上新的上传框。Schemas
对象的settings
属性,而不是修改ValidationFlags
属性。答案 1 :(得分:1)
以下是我用于使用本地模式验证xml的一大块代码:
string errors = string.Empty;
try
{
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(string.Empty, Page.MapPath("~/xml/Schema.xsd"));
XmlDocument doc = new XmlDocument();
doc.Schemas = schemas;
doc.Load(Page.MapPath("~/xml/sampleXML.xml"));
//use this line instead of the one above for a string in memory.
//doc.InnerXml = xmlToValidate;
ValidationEventHandler validator = delegate(object send, ValidationEventArgs ve)
{
errors += "\n" + ve.Severity + ": " + ve.Message;
};
doc.Validate(validator);
}
catch (XmlException xe)
{
errors += "\n" + xe.Message;
}
catch (XmlSchemaValidationException xe)
{
errors += "\n" + xe.Message;
}