Contact Yart for a relaxed conversation
Your Name * Message *
Your Email *  
Your Phone   
Our Phone:        03 8685 8718 (within Australia)
61 3 8685 8718 (outside Australia)
Contact Yart

Melbourne Content Management and Flash developers

 

for designers, agencies and your website

Resources / ASP NET / Validate XML Documents Against Schema
Validate XML Documents Against Schema Using .NET

This methods show how to ensure that an xml fragment valiates against a given xsd schema using C#.

You must convert the xml document to a TextReader class. This can be done as follows:

      StringWriter sw = new StringWriter();
      XmlTextWriter tw = new XmlTextWriter(sw);

      xmlDoc.WriteTo(tw);

      TextReader tr = new StringReader(sw.ToString());

  /// <summary>
  /// Validates an xml fragment given by a TextReader against the given namespace and xsd
  /// </summary>
  /// <param name="textReader">The xml fragment to validate</param>
  /// <param name="xmlns">The namespace of the xml</param>
  /// <param name="schemaPath">The location of the xsd relative to the application. E.g. xml/schema.xsd</param>
    private void ValidateXml(TextReader textReader, string xmlns, string schemaPath)
    {
      XmlReaderSettings settings = new XmlReaderSettings();
      XmlReader reader;
      ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

      settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
      settings.ValidationType = ValidationType.Schema;
      settings.Schemas.Add(xmlns, Server.MapPath(schemaPath));

      reader = XmlReader.Create(textReader, settings);

      while (reader.Read()) { }
     
    }

    private void ValidationEventHandler(object sender, ValidationEventArgs args)
    {
      validationErrors += args.Message;
    }

The latest at Yart
Search: