Use XmlReaderSettings to validate the Xml document

   
 


using System;
using System.Xml;
using System.Xml.Schema;

class ConsoleValidator {
    private bool failed;
    public bool Failed {
        get { return failed; }
    }

    public bool ValidateXml(string xmlFilename, string schemaFilename) {
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationType = ValidationType.Schema;

        XmlSchemaSet schemas = new XmlSchemaSet();
        settings.Schemas = schemas;
        schemas.Add(null, schemaFilename);
        settings.ValidationEventHandler += ValidationEventHandler;
        XmlReader validator = XmlReader.Create(xmlFilename, settings);
        failed = false;
        try {
            while (validator.Read()) { }
        } catch (XmlException err) {
            Console.WriteLine(err.Message);
            failed = true;
        } finally {
            validator.Close();
        }
        return !failed;
    }
    private void ValidationEventHandler(object sender, ValidationEventArgs args) {
        failed = true;
        Console.WriteLine("Validation error: " + args.Message);
    }
}

class MainClass {
    private static void Main() {
        ConsoleValidator consoleValidator = new ConsoleValidator();
        bool success = consoleValidator.ValidateXml("ProductCatalog.xml", "ProductCatalog.xsd");
        Console.WriteLine(success);
    }
}

           
         
     


Use XML schema to validate XML documents

   
 
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;

public class Validate {
  public static void Main(string [] args) {

    using (Stream stream = File.OpenRead(args[0])) {
      XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(stream));
      reader.ValidationType = ValidationType.Schema;
      reader.Schemas.Add("", args[1]);
      reader.ValidationEventHandler += new ValidationEventHandler(Handler);

      while (reader.Read()) {
      }
    }
    Console.WriteLine("Document is valid.");
  }

  public static void Handler(object sender, ValidationEventArgs e) {
    Console.WriteLine(e.Message);
  }
}

           
         
     


Validate Schema

   
 
using System;
using System.IO;
using System.Xml.Schema;

public class ValidateSchema {
  public static void Main(string [] args) {
    ValidationEventHandler handler = new ValidationEventHandler(ValidateSchema.Handler);
    XmlSchema schema = XmlSchema.Read(File.OpenRead(args[0]),handler);
    schema.Compile(handler);
  }

  public static void Handler(object sender, ValidationEventArgs e) {
    Console.WriteLine(e.Message);
  }
}

           
         
     


Validate an XML Document Against a Schema

   
 
using System;
using System.Xml;
using System.Xml.Schema;

public class ConsoleValidator {
    public static void ValidateXml(string xmlFilename, string schemaFilename) {
        XmlTextReader r = new XmlTextReader(xmlFilename);
        XmlValidatingReader validator = new XmlValidatingReader(r);
        validator.ValidationType = ValidationType.Schema;

        XmlSchemaCollection schemas = new XmlSchemaCollection();
        schemas.Add(null, schemaFilename);
        validator.Schemas.Add(schemas);

        validator.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
            
        try {
            while (validator.Read())
            {}
        }catch (XmlException err) {
            Console.WriteLine(err.Message);
        }finally {
            validator.Close();
        }
    }

    private static void ValidationEventHandler(object sender, ValidationEventArgs args) {
        Console.WriteLine("Validation error: " + args.Message);
    }
    private static void Main() {
        Console.WriteLine("Validating your.xml.");
        ValidateXml("your.xml", "your.xsd");
    }    
}

           
         
     


Choose ValidationType

   
 


using System;
using System.Xml;
using System.Xml.Schema;

class ConsoleValidator {
    private bool failed;
    public bool Failed {
        get { return failed; }
    }

    public bool ValidateXml(string xmlFilename, string schemaFilename) {
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationType = ValidationType.Schema;

        XmlSchemaSet schemas = new XmlSchemaSet();
        settings.Schemas = schemas;
        schemas.Add(null, schemaFilename);
        settings.ValidationEventHandler += ValidationEventHandler;
        XmlReader validator = XmlReader.Create(xmlFilename, settings);
        failed = false;
        try {
            while (validator.Read()) { }
        } catch (XmlException err) {
            Console.WriteLine(err.Message);
            failed = true;
        } finally {
            validator.Close();
        }
        return !failed;
    }
    private void ValidationEventHandler(object sender, ValidationEventArgs args) {
        failed = true;
        Console.WriteLine("Validation error: " + args.Message);
    }
}

class MainClass {
    private static void Main() {
        ConsoleValidator consoleValidator = new ConsoleValidator();
        bool success = consoleValidator.ValidateXml("ProductCatalog.xml", "ProductCatalog.xsd");
        Console.WriteLine(success);
    }
}

           
         
     


Set XmlReaderSettings

   
 


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;

public class MainClass {
    public static void Main() {
        XmlDocument doc = new XmlDocument();
        XmlReaderSettings rs = new XmlReaderSettings();
        rs.Schemas.Add(null, "books.xsd");
        rs.ValidationType = ValidationType.Schema;
        XmlReader rdr = XmlReader.Create("books.xml", rs);
        doc.Load(rdr);

        XPathNavigator nav = doc.CreateNavigator();

        if (nav.CanEdit) {
            XPathNodeIterator iter = nav.Select("/bookstore/book/price");
            while (iter.MoveNext()) {
                iter.Current.SetTypedValue("Invalid");
            }
        }
        doc.Save("newbooks.xml");

    }
}

           
         
     


XML write: element, attribute, cddata, namespace and entity reference

using System;
using System.IO;
using System.Text;
using System.Xml;

public class WriteXml {
public static void Main(string [] args) {
XmlTextWriter writer = new XmlTextWriter(Console.Out);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument(true);
writer.WriteComment(“this is a comment”);
writer.WriteStartElement(“root”);

writer.WriteAttributeString(“id”,”1″);
writer.WriteStartAttribute(“mynamespace”, “name”, “foo”);
writer.WriteString(“bar”);
writer.WriteEndAttribute();

// Write another element
writer.WriteElementString(“element1″,”some characters”);

writer.WriteStartElement(“cdataElement”);
writer.WriteAttributeString(“date”,DateTime.Now.ToString());
writer.WriteCData(“< & would choke on"); writer.WriteString("< & & & "); writer.WriteEndElement(); // Write an empty element writer.WriteStartElement("emptyElement"); writer.WriteEndElement(); // Write another empty element writer.WriteStartElement("emptyElement","Empty"); writer.WriteFullEndElement(); // Write some text writer.WriteString("One string "); writer.WriteEntityRef("amp"); writer.WriteString(" another."); // Close the root element writer.WriteEndElement(); // End the document writer.WriteEndDocument(); writer.Flush(); writer.Close(); } } [/csharp]