我正在针对可能不包含xmlns:其中的信息的模式验证XML文档。那么,如何将此类文档(或任何没有该架构信息的节点)标记为无效?我问,因为.NET只允许您验证XML文档中已正确识别的模式,并且我希望保证没有XML通过,这不符合模式。
如何验证此架构而无需添加属性,保存文件并重新加载?
例如,这有效:
xmlDoc.Load(file);
xmlDoc.DocumentElement.SetAttribute("xmlns", "http://test.mysite.com/schemas/myschemas");
xmlDoc.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema");
xmlDoc.DocumentElement.SetAttribute("xmlns:schemaLocation", "schemas/myschema.xsd");
xmlDoc.Save(file);
XmlSchema mySchema = XmlSchema.Read(XmlReader.Create("schemas/myschema.xsd"), settings_ValidationEventHandler);
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.Schemas.Add(mySchema);
settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);
XmlReader reader = XmlReader.Create(file, settings);
xmlDoc.Load(reader);
但这不是:
xmlDoc.Load(file);
xmlDoc.DocumentElement.SetAttribute("xmlns", "http://test.mysite.com/schemas/myschemas");
xmlDoc.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema");
xmlDoc.DocumentElement.SetAttribute("xmlns:schemaLocation", "schemas/myschema.xsd");
XmlSchema mySchema = XmlSchema.Read(XmlReader.Create("schemas/myschema.xsd"), settings_ValidationEventHandler);
xmlDoc.Schemas.Add(mySchema);
xmlDoc.Validate(settings_ValidationEventHandler);