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]

Read XML data from xml file: Node type, name

   

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

  class TestXMLReader
  {
    static void Main(string[] args)
    {
      TestXMLReader tstObj = new TestXMLReader();

      StreamReader myStream = new StreamReader("books.xml");
      XmlTextReader xmlTxtRdr = new XmlTextReader(myStream);
      while(xmlTxtRdr.Read())
      {
        if(xmlTxtRdr.NodeType == XmlNodeType.Element 
          &amp;&amp; xmlTxtRdr.Name == "A")
        {
          tstObj.ProcessMyDocument(xmlTxtRdr);
        }
      }

    }
    public void ProcessMyDocument(XmlTextReader reader)
    {
      Console.WriteLine("Start processing:" + reader.GetAttribute("property"));
      while(!(reader.NodeType == XmlNodeType.EndElement &amp;&amp; reader.Name == "B")
        &amp;&amp; reader.Read()) {
        if(reader.NodeType == XmlNodeType.Element &amp;&amp; reader.Name == "C") {
          Console.WriteLine("itemcode:" + reader.GetAttribute("c"));
        }
      }
    }
  }

/*
<books>
  <A property="a">
    <B>text</B>
    <C c="aaa" >textg</C>
    <D>99999</D>
  </A>
</books>
*/

           
          


XmlNodeType Text

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

class MainClass {
private static void Main() {
FileStream fs = new FileStream(“products.xml”, FileMode.Create);

XmlWriter w = XmlWriter.Create(fs);

w.WriteStartDocument();
w.WriteStartElement(“products”);

w.WriteStartElement(“product”);
w.WriteAttributeString(“id”, “1001”);
w.WriteElementString(“productName”, “Gourmet Coffee”);
w.WriteElementString(“productPrice”, “0.99”);
w.WriteEndElement();

w.WriteStartElement(“product”);
w.WriteAttributeString(“id”, “1002”);
w.WriteElementString(“productName”, “Blue China Tea Pot”);
w.WriteElementString(“productPrice”, “102.99”);
w.WriteEndElement();

w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();

fs = new FileStream(“products.xml”, FileMode.Open);

XmlReader r = XmlReader.Create(fs);

while (r.Read()) {
if (r.NodeType == XmlNodeType.Element) {
Console.WriteLine(“<" + r.Name + ">“);
if (r.HasAttributes) {
for (int i = 0; i < r.AttributeCount; i++) { Console.WriteLine(" ATTRIBUTE: " + r.GetAttribute(i)); } } } else if (r.NodeType == XmlNodeType.Text) { Console.WriteLine(" VALUE: " + r.Value); } } } } [/csharp]