geri222
6/13/2018 - 12:42 PM

XSD validation in memory

public void Xsd_whithout_saved(MemoryStream memoryXML, MemoryStream memoryXSD)
{
    //>>>Here is the biggest diference from the method Xsd_after_saved: I manipulate the XSD as string because it will come from database and 
    //it will not allowed to be saved locally
    XmlDocument xmlDoc = new XmlDocument();
    memoryXSD.Position = 0;
    xmlDoc.Load(memoryXSD);
    //In the futute, strArquivoInteiro will be fullfill by xsd comming from database as nvarchar(max) and I will not be allowed to save as a file locally
    string strArquivoInteiro = xmlDoc.OuterXml;

    byte[] byteArray = Encoding.ASCII.GetBytes(strArquivoInteiro);
    using (MemoryStream streamXSD = new MemoryStream(byteArray))
    using (StreamReader readerXsd = new StreamReader(streamXSD))
    {
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationEventHandler += validationEventHandler;
        settings.ValidationType = ValidationType.Schema;
        settings.Schemas.Add(null, XmlReader.Create(readerXsd));
        settings.CheckCharacters = true;

        using (XmlReader XmlValidatingReader = XmlReader.Create(memoryXML, settings))
        using (XmlTextReader Reader = new XmlTextReader(memoryXML))
        {
            XmlSchema Schema = new XmlSchema();

            streamXSD.Seek(0, SeekOrigin.Begin);
            Schema = XmlSchema.Read(readerXsd, validationEventHandler);

            XmlValidatingReader ValidatingReader = new XmlValidatingReader(Reader);
            ValidatingReader.ValidationType = ValidationType.Schema;
            ValidatingReader.Schemas.Add(Schema);

            try
            {
                XmlValidatingReader.Read();
                XmlValidatingReader.Close();

                ValidatingReader.ValidationEventHandler += validationEventHandler;

                while ((ValidatingReader.Read()))
                {
                }

                ValidatingReader.Close();
            }
            catch (Exception ex)
            {
                ValidatingReader.Close();
                XmlValidatingReader.Close();
            }
        }
    }
}