Possible to validate xml against xsd using code at runtime?

后端 未结 3 1883
一生所求
一生所求 2020-12-14 04:21

I have xml files that I read in at runtime, is is possible to validate the xml against an xsd file at runtime? using c#

相关标签:
3条回答
  • 2020-12-14 04:39

    I GOT CODE TOO! I use this in my tests:

        public static bool IsValid(XElement element, params string[] schemas)
        {
            XmlSchemaSet xsd = new XmlSchemaSet();
            XmlReader xr = null;
            foreach (string s in schemas)
            { // eh, leak 'em. 
                xr = XmlReader.Create(
                    new MemoryStream(Encoding.Default.GetBytes(s)));
                xsd.Add(null, xr);
            }
            XDocument doc = new XDocument(element);
            var errored = false;
            doc.Validate(xsd, (o, e) => errored = true);
            if (errored)
                return false;
    
            // If this doesn't fail, there's an issue with the XSD.
            XNamespace xn = XNamespace.Get(
                          element.GetDefaultNamespace().NamespaceName);
            XElement fail = new XElement(xn + "omgwtflolj/k");
            fail.SetAttributeValue("xmlns", xn.NamespaceName);
            doc = new XDocument(fail);
            var fired = false;
            doc.Validate(xsd, (o, e) => fired = true);
            return fired;
        }
    

    This one takes in the schemas as strings (file resources within the assembly) and adds them to a schema set. I validate and if its not valid I return false.

    If the xml isn't found to be invalid, I do a negative check to make sure my schemas aren't screwed up. Its not guaranteed foolproof, but I have used this to find errors in my schemas.

    0 讨论(0)
  • 2020-12-14 04:53

    simpler solution..

            try
            {
                XmlReaderSettings Xsettings = new XmlReaderSettings();
                Xsettings.Schemas.Add(null, "personDivideSchema.xsd");
                Xsettings.ValidationType = ValidationType.Schema;
    
                XmlDocument document = new XmlDocument();
                document.Load("person.xml");
    
                XmlReader reader = XmlReader.Create(new StringReader(document.InnerXml), Xsettings);
    
    
                while (reader.Read());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message.ToString());
            }
    
    0 讨论(0)
  • 2020-12-14 04:59

    Try this:

    public void ValidateXmlDocument(
        XmlReader documentToValidate, string schemaPath)
    {
        XmlSchema schema;
        using (var schemaReader = XmlReader.Create(schemaPath))
        {
            schema = XmlSchema.Read(schemaReader, ValidationEventHandler);
        }
    
        var schemas = new XmlSchemaSet();
        schemas.Add(schema);
    
        var settings = new XmlReaderSettings();
        settings.ValidationType = ValidationType.Schema;
        settings.Schemas = schemas;
        settings.ValidationFlags =
            XmlSchemaValidationFlags.ProcessIdentityConstraints |
            XmlSchemaValidationFlags.ReportValidationWarnings;
        settings.ValidationEventHandler += ValidationEventHandler;
    
        using (var validationReader = XmlReader.Create(documentToValidate, settings))
        {
            while (validationReader.Read())
            {
            }
        }
    }
    
    private static void ValidationEventHandler(
        object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Error)
        {
            throw args.Exception;
        }
    
        Debug.WriteLine(args.Message);
    }
    
    0 讨论(0)
提交回复
热议问题