Getting started with XSD validation with .NET

前端 未结 3 1645
鱼传尺愫
鱼传尺愫 2020-12-14 09:27

Here is my first attempt at validating XML with XSD.

The XML file to be validated:




        
3条回答
  •  無奈伤痛
    2020-12-14 09:53

    Following is out of a working sample:

    Usage:

    XMLValidator val = new XMLValidator();
    if (!val.IsValidXml(File.ReadAllText(@"d:\Test2.xml"), @"D:\Test2.xsd"))
       MessageBox.Show(val.Errors);
    

    Class:

    public class CXmlValidator
    {
        private int nErrors = 0;
        private string strErrorMsg = string.Empty;
        public string Errors { get { return strErrorMsg; } }
        public void ValidationHandler(object sender, ValidationEventArgs args)
        {
            nErrors++;
            strErrorMsg = strErrorMsg + args.Message + "\r\n";
        }
    
        public bool IsValidXml(string strXml/*xml in text*/, string strXsdLocation /*Xsd location*/)
        {
            bool bStatus = false;
            try
            {
                // Declare local objects
                XmlTextReader xtrReader = new XmlTextReader(strXsdLocation);
                XmlSchemaCollection xcSchemaCollection = new XmlSchemaCollection();
                xcSchemaCollection.Add(null/*add your namespace string*/, xtrReader);//Add multiple schemas if you want.
    
                XmlValidatingReader vrValidator = new XmlValidatingReader(strXml, XmlNodeType.Document, null);
                vrValidator.Schemas.Add(xcSchemaCollection);
    
                // Add validation event handler
                vrValidator.ValidationType = ValidationType.Schema;
                vrValidator.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);
    
                //Actual validation, read conforming the schema.
                while (vrValidator.Read()) ;
    
                vrValidator.Close();//Cleanup
    
                //Exception if error.
                if (nErrors > 0) { throw new Exception(strErrorMsg); }
                else { bStatus = true; }//Success
            }
            catch (Exception error) { bStatus = false; }
    
            return bStatus;
        }
    }
    

    The above code validates following xml(code3) against xsd(code4).

    
    
    My Name 1, My Street Address Far Mali

    In validating against your xml/xsd I get of errors different than yours; I think this can help you continue(add/remove xml elements) from here:

    Errors

    You may also try the reverse process; try generating the schema from your xml and compare with your actual xsd - see the difference; and the easiest way to do that is to use generate schema using VS IDE. Following is how you'd do that:

    Hope this helps.

    --EDIT--

    This is upon John's request, please see updated code using non deprecated methods:

    public bool IsValidXmlEx(string strXmlLocation, string strXsdLocation)
    {
        bool bStatus = false;
        try
        {
            // Declare local objects
            XmlReaderSettings rs = new XmlReaderSettings();
            rs.ValidationType = ValidationType.Schema;
            rs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ReportValidationWarnings;
            rs.ValidationEventHandler += new ValidationEventHandler(rs_ValidationEventHandler);
            rs.Schemas.Add(null, XmlReader.Create(strXsdLocation));
    
            using (XmlReader xmlValidatingReader = XmlReader.Create(strXmlLocation, rs))
            { while (xmlValidatingReader.Read()) { } }
    
            ////Exception if error.
            if (nErrors > 0) { throw new Exception(strErrorMsg); }
            else { bStatus = true; }//Success
        }
        catch (Exception error) { bStatus = false; }
    
        return bStatus;
    }
    
    void rs_ValidationEventHandler(object sender, ValidationEventArgs e)
    {
        if (e.Severity == XmlSeverityType.Warning) strErrorMsg += "WARNING: " + Environment.NewLine;
        else strErrorMsg += "ERROR: " + Environment.NewLine;
        nErrors++;
        strErrorMsg = strErrorMsg + e.Exception.Message + "\r\n";
    }
    

    Usage:

    if (!val.IsValidXmlEx(@"d:\Test2.xml", @"D:\Test2.xsd"))
                    MessageBox.Show(val.Errors);
                else
                    MessageBox.Show("Success");
    

    Test2.XML

    
    
      
        SampleVariant
      
      
        LegendaryMode
      
      
        AmazingMode
      
    
    

    Test2.XSD (Generated from VS IDE)

    
    
      
        
          
            
              
                
                  
                  
                
              
            
          
        
      
    
    

    This is guaranteed to work!

提交回复
热议问题