Validate Xml - CSharp System.Xml

CSharp examples for System.Xml:XML Reader

Description

Validate Xml

Demo Code


using System.Xml.Schema;
using System.Xml;
using System.IO;/*from  ww  w .j  av  a  2s. c  o  m*/
using System.Collections;
using System;

public class Main{
        public static void ValidateXml(XmlDocument xmlDocument, XmlSchema xsdSchema)
    {
      MemoryStream stream1 = null;
      MemoryStream stream2 = null;
      try
      {
        stream1 = new MemoryStream();
        xmlDocument.Save(stream1);
        stream1.Position = 0;
        ValidateXml(stream1, xsdSchema);
      }
      finally
      {
        if (stream2 != null)
        {
          stream2.Close();
        }
        if (stream1 != null)
        {
          stream1.Close();
        }
      }
    }
        public static void ValidateXml(Stream xmlStream, XmlSchema xsdSchema)
    {
      XmlTextReader reader1 = null;
      try
      {
        reader1 = new XmlTextReader(xmlStream);
        XmlSchemaCollection collection1 = new XmlSchemaCollection();
        collection1.Add(xsdSchema);
        XmlValidatingReader reader2 = new XmlValidatingReader(reader1);
        reader2.ValidationType = ValidationType.Schema;
        reader2.Schemas.Add(collection1);
        ArrayList list1 = new ArrayList();
        while (reader2.ReadState != ReadState.EndOfFile)
        {
          try
          {
            reader2.Read();
            continue;
          }
          catch (XmlSchemaException exception1)
          {
            list1.Add(exception1);
            continue;
          }
        }
        if (list1.Count != 0)
        {
          throw new XmlValidationException(list1);
        }
      }
      catch (XmlValidationException exception2)
      {
        throw exception2;
      }
      catch (Exception exception3)
      {
        throw new XmlValidationException(exception3.Message, exception3);
      }
      finally
      {
        if (reader1 != null)
        {
          reader1.Close();
        }
      }
    }
}

Related Tutorials