1

我正在针对可能不包含 xmlns:information 的架构验证 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);
4

0 回答 0