Generating XML Schema Dynamically Using VB.NET 2005: Essentials

This is the first article in a series concentrating on generating XML Schema dynamically using Visual Basic 2005. The series is mainly targeted at those who are familiar with XML, XML Schema and the .NET framework.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 37
February 06, 2006
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

 A downloadable file for this article is available here.

There exist several articles on XML alone on this website.  If you are new to XML Schema, I strongly suggest you go through my series “Designing your own XML Schema.” That series will introduce you to all the necessary concepts in designing XML schemas, even if you are a beginner.

The entire solution for this article was developed using Visual Studio 2005 Professional Edition on Windows Server 2003 standard edition.  Some examples in this series may not compile successfully using Visual Studio 2003, as some of the features in .NET 1.1 turned out to be obsolete in .NET 2.0.  For complete details you can refer to the link http://go.microsoft.com/fwlink/?linkid=14202

Generating XML Schema dynamically using the .NET framework: preliminaries

Not everyone knows that we can generate XML schema dynamically using the .NET framework.  This happened to be the situation in one of my projects.  And I just wanted to share my knowledge with you.  I experienced few troubles when I ported my .NET 1.1 applications to .NET 2.0 (due to obsolescence).  During this series, we shall explore and address the most important issues on this topic.

First of all, we need to import two namespaces, namely “System.Xml” and “System.Xml.Schema”.  Both of them are available in the “System.Xml” assembly.  So, we need to refer (using “Add Reference”) to “System.Xml” before importing the two namespaces.

For this sample, I just created a simple Windows application using Visual Studio with a single button and multi-lined textbox.  When I hit the button it would generate some XML Schema in the multi-lined textbox.  So, I suggest you design the same before you proceed with the code.

Now let us consider that I would like to have the following XML Schema to be generated:

<?xml version="1.0" encoding="utf-16"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Organization" type="xs:string" />
</xs:schema>

The above XML Schema simply declares a single element, “Organization.”  To generate the above XML Schema dynamically, copy and paste the following code and execute it with the application:

Imports System
Imports System.Xml
Imports System.Xml.Schema
.
.
.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
        Me.TextBox1.Text = ""
        Dim schema As New XmlSchema()
        Dim elementOrg As New XmlSchemaElement()
        schema.Items.Add(elementOrg)
        elementOrg.Name = "Organization"
        elementOrg.SchemaTypeName = New XmlQualifiedName
("string", "http://www.w3.org/2001/XMLSchema")
        Dim nsmgr As New XmlNamespaceManager(New NameTable())
        nsmgr.AddNamespace("xs",
"http://www.w3.org/2001/XMLSchema")
        Dim sw As New IO.StringWriter
        schema.Write(sw, nsmgr)
        Me.TextBox1.Text = sw.ToString
    End Sub

That’s it.  Just execute the application and hit the button. It will show the previous XML Schema in to the textbox.  You can find an explanation for the above code in the next section.

Understanding the dynamic generation of XML Schema using the .NET framework

This section explains the code fragment listed in the previous section.  Let us examine it part by part.  First consider the following:

Imports System
Imports System.Xml
Imports System.Xml.Schema

The above makes class libraries (related to XML) available for our application.  We shall clear the textbox information using the following statement:

Me.TextBox1.Text = ""

Proceeding further, we have the following statement:

Dim schema As New XmlSchema()

The above statement really starts our XML Schema.  It creates an object (“schema”) of type “XmlSchema.”  The class “XmlSchema” basically exists in the namespace “System.Xml.Schema,” which resides in “System.XML.dll” assembly.  This would indirectly add the top most processing instruction, which defines the XML document version, and so on.

Once a schema object is created, we can start adding our own elements, attributes, processing instructions, comments, and so on to the same schema object.  Further proceeding, we have the following:

Dim elementOrg As New XmlSchemaElement()

The above statement creates a simple XML Schema element (but no descriptions of the element yet!).  Further proceeding we have:

        schema.Items.Add(elementOrg)
        elementOrg.Name = "Organization"
        elementOrg.SchemaTypeName = New XmlQualifiedName
("string", "http://www.w3.org/2001/XMLSchema")

The first statement from the above code fragment adds the element “elementOrg” to the schema (which we already created at the top).  The second and third statements determine the characteristics of the element “elementOrg.”  The second statement assigns the element name and the third defines the “data type” with respect to the definitions available at http://www.w3.org/2001/XMLSchema.  Further proceeding, we have the following 

        Dim nsmgr As New XmlNamespaceManager(New NameTable())
        nsmgr.AddNamespace("xs",
"http://www.w3.org/2001/XMLSchema")

The above two statements are used to define the namespace to which our schema is adhered. Further proceeding we have the following:

        Dim sw As New IO.StringWriter
        schema.Write(sw, nsmgr)
        Me.TextBox1.Text = sw.ToString

The above code fragment creates a string writer where the schema is generated (using the namespace we defined earlier).  Once the schema generation is complete we finally display it using the last line.

Generating XML Schema dynamically using the .NET framework: complex type

Since I covered the basics in the previous sections, we shall now focus on “complex types” in XML Schema.  Generating “complex types” is a bit more complicated than generating “simple types.”  Let us consider the following XML Schema:

<?xml version="1.0" encoding="utf-16"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Employee">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="ID" type="xs:int" />
        <xs:element name="Name" type="xs:string" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

I know that the above XML schema is not at all practical.  But I will be using it only for demonstration.  I meant it only to explain the .NET code better (and not XML Schema).  To generate the above XML Schema dynamically, we can consider the following code:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
        Me.TextBox1.Text = ""
        Dim schema As New XmlSchema()
 
        Dim eEmployee As New XmlSchemaElement()
        schema.Items.Add(eEmployee)
        eEmployee.Name = "Employee"
 
        Dim ctEmployee As New XmlSchemaComplexType()
        eEmployee.SchemaType = ctEmployee
 
        Dim sqEmployee As New XmlSchemaSequence
        ctEmployee.Particle = sqEmployee
 
        Dim eID As New XmlSchemaElement()
        sqEmployee.Items.Add(eID)
        eID.Name = "ID"
        eID.SchemaTypeName = New XmlQualifiedName("int",
"http://www.w3.org/2001/XMLSchema")
 
        Dim eName As New XmlSchemaElement()
        sqEmployee.Items.Add(eName)
        eName.Name = "Name"
        eName.SchemaTypeName = New XmlQualifiedName("string",
"http://www.w3.org/2001/XMLSchema")
 
        Dim nsmgr As New XmlNamespaceManager(New NameTable())
        nsmgr.AddNamespace("xs",
"http://www.w3.org/2001/XMLSchema")
        Dim sw As New IO.StringWriter
        schema.Write(sw, nsmgr)
        Me.TextBox1.Text = sw.ToString
 
    End Sub

I purposely excluded the “import” statements, as I already covered those in previous sections.  You can find the explanation of the above code in the next section.

Understanding the dynamic generation of complex type in XML Schema

This section explains the code fragment listed in the previous section.  Let us examine it part by part.  We shall clear the textbox information using the following statement:

Me.TextBox1.Text = ""

Proceeding further, we have the following statement:

Dim schema As New XmlSchema()

The above statement starts our XML Schema.  Once a schema object is created, we can start adding our own elements, attributes, processing instructions, comments, and so on to the same schema object.  Further proceeding, we have the following: 

        Dim eEmployee As New XmlSchemaElement()
        schema.Items.Add(eEmployee)
        eEmployee.Name = "Employee"

The above code fragment simply creates a new element called “Employee” and adds it to the schema generator.  Further proceeding we have:

        Dim ctEmployee As New XmlSchemaComplexType()
        eEmployee.SchemaType = ctEmployee
        Dim sqEmployee As New XmlSchemaSequence
        ctEmployee.Particle = sqEmployee

As “Employee” is of the “complex type” (and not “simple type”), we need to specify this point.  A complex type should also be joined with a “particle.”  The “particle” could be any of “All,” “Sequence,” “Choice” and so on (which I already explained in my “Designing your own XML Schema” Series). 

The above code fragment creates a new complex type (for the “Employee” element) and a “sequence particle” (which means that the elements should be provided in an orderly fashion).  Further proceeding, we have the following:

        Dim eID As New XmlSchemaElement()
        sqEmployee.Items.Add(eID)
        eID.Name = "ID"
        eID.SchemaTypeName = New XmlQualifiedName("int",
"http://www.w3.org/2001/XMLSchema")

A “particle” generally contains the nested elements inside it (not every particle may contain nested elements as well).  In our case, the “Employee” element needs to be nested with two more elements (child elements), “ID” and “Name.” 

The above code fragment creates a new element, names it “ID,” defines it as an integer data type, and finally adds it to the “sequence particle.”  Similarly, we add the “Name” element as follows:

        Dim eName As New XmlSchemaElement()
        sqEmployee.Items.Add(eName)
        eName.Name = "Name"
        eName.SchemaTypeName = New XmlQualifiedName("string",
"http://www.w3.org/2001/XMLSchema")

Further proceeding, we have the following

        Dim nsmgr As New XmlNamespaceManager(New NameTable())
        nsmgr.AddNamespace("xs",
"http://www.w3.org/2001/XMLSchema")

The above two statements are used to define the namespace to which our schema gets adhered.  Proceeding further we have the following:

        Dim sw As New IO.StringWriter
        schema.Write(sw, nsmgr)
        Me.TextBox1.Text = sw.ToString

The above code fragment creates a string writer where the schema is generated (using the namespace we defined earlier).  Once the schema generation is complete we finally display it using the last line.

I hope that this article gives you a kick-start in generating dynamic XML Schemas using the .NET framework.  Another issue to pay attention to is that the examples I used in this demonstration may not be helpful in practical (or production) scenarios.  I strongly suggest you have a proper working draft design of the XML Schema you wanted to generate, and finally generate it using the code I present in this series.  A working draft may not be necessary if you want to generate the XML Schema from existing relational databases or other, similar kinds of structured information sources.

Any comments, suggestions, feedback, bugs, errors, enhancements are highly appreciated at jag_chat@yahoo.com

blog comments powered by Disqus
XML ARTICLES

- More on Triggers and Styles and Control Temp...
- Looking at Triggers with Styles and Control ...
- A Closer Look at Styles and Control Templates
- Styles and Control Templates
- Properties and More in XAML
- Elements and Attributes in XAML
- XAML in a Nutshell
- Importing XML Files into Access 2007
- Using MSXML3.0 with VB 6.0
- MSXML, concluded
- MSXML, continued
- MSXML Tutorial
- Generating XML Schema Dynamically Using VB.N...
- XSL Transformations using ASP.NET
- Applying XSLT to XML Using ASP.NET

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 9 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials