MPDL
Computing Research Methods Multi-Perspective Digital Library

Guests are welcome to view our materials. To subscribe, edit, view raw markup, etc., you'll need to register for an account. Accounts are free (and will always be free) - your involvement helps us directly and indirectly (by demonstrating that our work matters to our funders...) StartingPoints has more info.
MPDL

Final Lab Report

1. My simple code in C# to create XML Schema

using System;
using System.Xml;
using System.IO;
using System.Text;
public class ReadWriteXml
{
    private static void Main()
    {
        FileStream fs = new FileStream("products.xml", FileMode.Create);
        XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);      

        w.WriteStartDocument();

        //First Elelment added
        w.WriteComment("My First XML Comment");
        w.WriteStartElement("products");
        w.WriteStartElement("product");
        w.WriteAttributeString("id", "01");
        w.WriteElementString("name", "C#");
        w.WriteElementString("price", "0.99");
        w.WriteElementString("lists", "C#,Java,C++");     
        w.WriteEndElement();

        //Second Element Added
        w.WriteComment("My First XML Comment");
        w.WriteStartElement("Product2");
        w.WriteStartElement("product2");
        w.WriteAttributeString("Number", "02");
        w.WriteElementString("Name", "C#");
        w.WriteElementString("prices", "1.99");
        w.WriteElementString("Lists", "C++");
        w.WriteEndElement(); 
      
        //w.WriteEndElement();       
        w.WriteEndDocument();
        w.Flush();
        fs.Close();

        Console.WriteLine("Document created.");
        fs = new FileStream("products.xml", FileMode.Open);
        XmlTextReader r = new XmlTextReader(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("\tATTRIBUTE: " + r.GetAttribute(i));
                    }
                }
            }
            else if (r.NodeType == XmlNodeType.Text)
            {
                Console.WriteLine("\tVALUE: " + r.Value);
            }
        }
    }
}
This will create an XML whose name is Products.XML

XML SCHEMA VALIDATOR PROGRAM IN C#

The XML Schema Validator checks if a given XML document is well formed and has a valid schema. If the document is not a valid XML schema, it generates the error describing the problem in the schema.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Xml;
using System.Xml.Schema;

namespace Xsd_example
{
   
   public class Form1 : System.Windows.Forms.Form
   {
      private System.ComponentModel.Container components = null;
      private static bool isValid;
      private static string error;
      private static string header;
      private System.Windows.Forms.Label label1;
      private System.Windows.Forms.Button validate;
      private System.Windows.Forms.Label result;
      private System.Windows.Forms.Button fileBrowse;
      private System.Windows.Forms.OpenFileDialog openFileDialog;
      private System.Windows.Forms.RichTextBox resultErrors;
      private System.Windows.Forms.RadioButton documentTypeSchema;
      private System.Windows.Forms.RadioButton documentTypeDTD;
      private System.Windows.Forms.RadioButton documentTypeNone;
      private System.Windows.Forms.TextBox file;

      public Form1()
      {
         InitializeComponent();
      }
      
      protected override void Dispose( bool disposing )
      {
         if( disposing )
         {
            if (components != null) 
            {
               components.Dispose();
            }
         }
         base.Dispose( disposing );
      }

      #region Windows Form Designer generated code
      
      private void InitializeComponent()
      {
         this.label1 = new System.Windows.Forms.Label();
         this.file = new System.Windows.Forms.TextBox();
         this.validate = new System.Windows.Forms.Button();
         this.result = new System.Windows.Forms.Label();
         this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
         this.fileBrowse = new System.Windows.Forms.Button();
         this.resultErrors = new System.Windows.Forms.RichTextBox();
         this.documentTypeSchema = new System.Windows.Forms.RadioButton();
         this.documentTypeDTD = new System.Windows.Forms.RadioButton();
         this.documentTypeNone = new System.Windows.Forms.RadioButton();
         this.SuspendLayout();

         // label1         
         this.label1.Location = new System.Drawing.Point(8, 16);
         this.label1.Name = "label1";
         this.label1.Size = new System.Drawing.Size(100, 16);
         this.label1.TabIndex = 0;
         this.label1.Text = "XML filename";
         
         // file         
         this.file.Location = new System.Drawing.Point(8, 48);
         this.file.Name = "file";
         this.file.Size = new System.Drawing.Size(192, 20);
         this.file.TabIndex = 1;
         this.file.Text = "";
         this.file.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
         this.file.WordWrap = false;
          
         // validate         
         this.validate.Location = new System.Drawing.Point(72, 112);
         this.validate.Name = "validate";
         this.validate.Size = new System.Drawing.Size(112, 24);
         this.validate.TabIndex = 2;
         this.validate.Text = "&Validate";
         this.validate.Click += new System.EventHandler(this.validate_Click);
          
         // result         
         this.result.Location = new System.Drawing.Point(72, 144);
         this.result.Name = "result";
         this.result.Size = new System.Drawing.Size(120, 32);
         this.result.TabIndex = 3;
          
         // openFileDialog         
         this.openFileDialog.FileOk += new System.ComponentModel.CancelEventHandler(this.BrowserSelection);
          
         // fileBrowse         
         this.fileBrowse.Location = new System.Drawing.Point(208, 48);
         this.fileBrowse.Name = "fileBrowse";
         this.fileBrowse.Size = new System.Drawing.Size(56, 16);
         this.fileBrowse.TabIndex = 5;
         this.fileBrowse.Text = "Browser";
         this.fileBrowse.Click += new System.EventHandler(this.fileBrowse_Click);
         
         // resultErrors          
         this.resultErrors.Location = new System.Drawing.Point(8, 192);
         this.resultErrors.Name = "resultErrors";
         this.resultErrors.Size = new System.Drawing.Size(248, 144);
         this.resultErrors.TabIndex = 6;
         this.resultErrors.Text = "";
          
         // documentTypeSchema         
         this.documentTypeSchema.Checked = true;
         this.documentTypeSchema.Location = new System.Drawing.Point(24, 80);
         this.documentTypeSchema.Name = "documentTypeSchema";
         this.documentTypeSchema.Size = new System.Drawing.Size(64, 24);
         this.documentTypeSchema.TabIndex = 7;
         this.documentTypeSchema.TabStop = true;
         this.documentTypeSchema.Text = "Schema";
          
         // documentTypeDTD         
         this.documentTypeDTD.Location = new System.Drawing.Point(112, 80);
         this.documentTypeDTD.Name = "documentTypeDTD";
         this.documentTypeDTD.Size = new System.Drawing.Size(48, 24);
         this.documentTypeDTD.TabIndex = 8;
         this.documentTypeDTD.Text = "DTD";
          
         // documentTypeNone         
         this.documentTypeNone.Location = new System.Drawing.Point(184, 80);
         this.documentTypeNone.Name = "documentTypeNone";
         this.documentTypeNone.Size = new System.Drawing.Size(56, 24);
         this.documentTypeNone.TabIndex = 9;
         this.documentTypeNone.Text = "None";
          
         // Form1         
         this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
         this.ClientSize = new System.Drawing.Size(272, 349);
         this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                        this.documentTypeNone,this.documentTypeDTD, this.documentTypeSchema,this.resultErrors,this.fileBrowse,this.result,this.validate,this.file,this.label1});
      this.Name = "Form1";
      this.Text = "Form1";
      this.Load += new System.EventHandler(this.Form1_Load);
      this.ResumeLayout(false);
      }

      #endregion      
      [STAThread]
      static void Main() 
      {
         Application.Run(new Form1());
      }

      private void Form1_Load(object sender, System.EventArgs e)
      {
         file.Text = System.Environment.CurrentDirectory;
      }

      private void validate_Click(object sender, System.EventArgs e)
      {
         //reset UI information
         error = "";
         result.Text ="";
         resultErrors.Text = "";
         isValid = true;
         header = "";

         try 
         {
            XmlTextReader xml = new XmlTextReader(file.Text);
            XmlValidatingReader xsd = new XmlValidatingReader(xml);

            //use schemas or DTDs
            if (documentTypeSchema.Checked == true)
            {
               //schemas
               xsd.ValidationType = ValidationType.Schema;
            }
            else if (documentTypeNone.Checked == true)
            {
               //see if your XML is well formed?
               xsd.ValidationType = ValidationType.None;
            }
            else
            {
               //why do you want to learn this? its old, no one uses it and they are laughing behind your back. Shame on you!
               xsd.ValidationType = ValidationType.DTD;
            }

            //and validation errors events go to.
            xsd.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler);
            
            //wait until the read is over.
            while (xsd.Read())
            {
            }
            xsd.Close();

            // Check whether the document is valid or invalid.
            if (isValid)
               header = "Valid Document";
            else
               header = "Invalid Document";
         }
         catch(UnauthorizedAccessException a)
         {
            //dont have access permission
            error = a.Message;
         }
         catch(Exception a)
         {
            //and other things that could go wrong
            error = a.Message;
         }
         resultErrors.Text = error;
         result.Text = header;
      }

      //handle our validation errors
      public static void MyValidationEventHandler(object sender, 
         ValidationEventArgs args) 
      {
         isValid = false;
         error += args.Message + "\n\n";
      }

      //start file browser 
      private void fileBrowse_Click(object sender, System.EventArgs e)
      {
         openFileDialog.Multiselect = false;
         openFileDialog.Filter = "XML(*.xml)|*.xml";
         openFileDialog.InitialDirectory = file.Text;
         openFileDialog.ShowDialog(this);
      }

      //clicked on from file browser, clicking cancel wil return from the showDialog
      private void BrowserSelection(object sender, System.ComponentModel.CancelEventArgs e)
      {         
         file.Text = openFileDialog.FileName;
         openFileDialog.Dispose();
      }


   }

}

The above code uses Xml.Schema namespace to do do validation process.This program can validate Schema and DTD (obsolete!).The ValidationType? property on the XmlReaderSettings? class determine whether the XmlReader? instance enforces validation.


<?xml version="1.0" encoding="UTF-8" ?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="body">
<xs:complexType mixed="true" />
</xs:element>
<xs:element name="product id">
<xs:complexType mixed="true" />
</xs:element>

<xs:element name="name">
<xs:complexType mixed="true" />
</xs:element>

<xs:element name="price">
<xs:complexType mixed="true" />
</xs:element>

<xs:element name="lists">
<xs:complexType mixed="true" />
</xs:element>

<xs:element name="products">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="product id" />
        <xs:element ref="name" />
        <xs:element ref="price" />
        <xs:element ref="lists" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  • XMLValidator.jpg:
    XMLValidator.jpg

-- PrathibhaMethil - 13 Nov 2008

r3 - 18 Nov 2008 - 12:32:17 - PrathibhaMethil
Guests are welcome to view our materials. To subscribe, edit, view raw markup, etc., you'll need to register for an account. Accounts are free (and will always be free) - your involvement helps us directly and indirectly (by demonstrating that our work matters to our funders...) StartingPoints has more info.
This site is powered by the TWiki collaboration platformCopyright 1999-2009 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding Ahatwiki? Send feedback Syndicate this site RSSATOM