Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Xml架构验证在C中使用MemoryStream失败#_C#_Xml_Validation_Xsd - Fatal编程技术网

C# Xml架构验证在C中使用MemoryStream失败#

C# Xml架构验证在C中使用MemoryStream失败#,c#,xml,validation,xsd,C#,Xml,Validation,Xsd,这是我的功能 如果将MemoryStream传递给XmlReader,它有时不会验证正确的xml文件。我将XmlDocument对象存储在内存中,我希望根据最终用户提供的xsd模式文件对其进行验证 ValidateSchema1(string XMLPath, string XSDPath) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(XMLPath);

这是我的功能

如果将MemoryStream传递给XmlReader,它有时不会验证正确的xml文件。我将XmlDocument对象存储在内存中,我希望根据最终用户提供的xsd模式文件对其进行验证

ValidateSchema1(string XMLPath, string XSDPath)
    {
        XmlDocument xmlDocument = new XmlDocument();

        xmlDocument.Load(XMLPath);

          using (MemoryStream mstream = new MemoryStream())
          {
              //StreamWriter writer = new StreamWriter(mstream);
              xmlDocument.Save(mstream);
              mstream.Seek(0, SeekOrigin.Begin);
              XmlSchemaSet sc = new XmlSchemaSet();

              // Add the schema to the collection.
              sc.Add(null, XSDPath);

              // Set the validation settings.
              XmlReaderSettings settings = new XmlReaderSettings();
              settings.ValidationType = ValidationType.Schema;
              settings.Schemas = sc;
              settings.ValidationEventHandler += ValidationCallBack;

              // Create the XmlReader object.

              // Not woking
              XmlReader reader = XmlReader.Create(mstream, settings);

              // Working
              //XmlReader reader = XmlReader.Create(new StringReader(xmlDocument.InnerXml), settings);

              // Working
              //XmlReader reader = XmlReader.Create(XMLPath, settings);

              // Parse the file. 
              while (reader.Read()) ;
          }

    }
这可能会奏效:
这很有效

编辑1:修复了您提供的代码,现在代码正常工作,验证了我的2个文件。出现错误的原因是,您试图用它自己验证和Xsd,但根元素不存在。请自己查看解决方案

public void Xsd_whithout_saved()  
    {  
        XmlDocument xmlDoc = new XmlDocument();  
        xmlDoc.Load(@"file.xsd");  
        //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);
        MemoryStream streamXSD = new MemoryStream(byteArray);
        //<<<
        streamXSD.Position = 0;
        StreamReader readerXsd = new StreamReader(streamXSD);

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationEventHandler += this.MyValidationEventHandler;

        settings.ValidationType = ValidationType.Schema;
        settings.Schemas.Add(null, XmlReader.Create(readerXsd));
        settings.CheckCharacters = true;

        XmlReader XmlValidatingReader = XmlReader.Create(@"file.xml", settings);

        XmlTextReader Reader = new XmlTextReader(@"file.xsd");
        //Created another reader for xml to use for validation
        XmlTextReader Reader2 = new XmlTextReader(@"file.xml");

        XmlSchema Schema = new XmlSchema();

        //IN THIS LINE I RECEIVED THE XmlException "Root Element is Missing" and I can't understand the reason
        //This was the first problem, a xsd root element isn't equal to an xml root element , and you where trying to validate and xsd with xsd here, and of course the error.
        Schema = XmlSchema.Read(Reader, MyValidationEventHandler);

        XmlValidatingReader ValidatingReader = new XmlValidatingReader(Reader2);

        ValidatingReader.ValidationType = ValidationType.Schema;

        ValidatingReader.Schemas.Add(Schema);

        try
        {

            XmlValidatingReader.Read();
            XmlValidatingReader.Close();

            ValidatingReader.ValidationEventHandler += MyValidationEventHandler;

            while ((ValidatingReader.Read()))
            {

            }

            ValidatingReader.Close();
        }
        catch (Exception ex)
        {
            ValidatingReader.Close();
            XmlValidatingReader.Close();
        }
    }
public void Xsd_whithout_saved()
{  
XmlDocument xmlDoc=新的XmlDocument();
Load(@“file.xsd”);
//在未来,strArquivoInteiro将由数据库中的xsd提交以nvarchar(max)的形式填充,并且我将//不被允许在本地保存为文件
字符串strarquiviointeiro=xmlDoc.OuterXml;
byte[]byteArray=Encoding.ASCII.GetBytes(strArquivoInteiro);
MemoryStream streamXSD=新的MemoryStream(byteArray);

// 为什么不在代码中使用另外两个注释掉的方法而不是内存流

[更新]:

试试这个答案:

    public static bool ValidateXmlFromXsd(string xml, string xsdFile)
    {

        bool returned = false;
        XmlValidatingReader reader = null;
        XmlSchemaCollection myschema = new XmlSchemaCollection();
        ValidationEventHandler eventHandler = new ValidationEventHandler(ShowCompileErrors);
        try
        {
            XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);
            reader = new XmlValidatingReader(xml, XmlNodeType.Element, context);
            myschema.Add("urn:schemas-microsoft-com:xml-msdata", xsdFile);
            reader.ValidationType = ValidationType.Schema;
            reader.Schemas.Add(myschema);

            while (reader.Read()) { }

            Console.WriteLine("Completed validating xmlfragment");
            returned = true;
        }
        catch (XmlException XmlExp)
        {
            Console.WriteLine(XmlExp.Message);
        }
        catch (XmlSchemaException XmlSchExp)
        {
            Console.WriteLine(XmlSchExp.Message);
        }
        catch (Exception GenExp)
        {
            Console.WriteLine(GenExp.Message);
        }
        finally
        {
            Console.Read();
        }
        return returned;
    }

验证失败时,您确定XML有效吗?验证异常应该告诉您失败的原因。因为提供的解决方案无法用于我已有的类。我可以问一下否决的原因吗?这只是一个建议,不是答案!您可以发表评论,而不是回答。我回家后将尝试此操作。不幸的是elly没有。还有一个问题,几乎所有你使用的类都过时了,很快它们就会消失