Generating XML Schema Dynamically Using VB.NET 2005: Essentials - Generating XML Schema dynamically using the .NET framework: complex type
(Page 3 of 4 )
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.
Next: Understanding the dynamic generation of complex type in XML Schema >>
More XML Articles
More By Jagadish Chaterjee