Click here to Skip to main content
11,578,241 members (67,250 online)
Click here to Skip to main content

Creating an XML file based on XSD

, 16 Oct 2006 CPOL 115.4K 3.1K 23
Rate this:
Please Sign up or sign in to vote.
An article which describes creating an XML file based on a schema.

Introduction

This article will be successful in explaining you how to generate an XML file based on the schema you have.

Background

I really had a couple of bad days goggling and trying out to generate an XML file based on the schema I am given with. I successfully loaded the dataset from SQL which contains the data necessary for generating the XML file but I was unable to bind it to the format I needed. Being a software engineer, I thought if it was possible to hard-code it and write it as a text file? Good heavens, I came across the XSD.exe tool which comes along with the SDK of Visual Studio. The tool generates a class file which will return a dataset of the structure described in the schema. So once you have set all the properties you can play around

Using the code

You can find XSD.exe in the "bin" folder of the SDK of Visual Studio (if you are not using Visual Studio, I am attaching the EXE file for you). You can generate the code in any .NET supported language (you can find them by running xsd/? in the prompt). As I work with VB.NET, I will provide you the sample in VB. I have a schema file named "schema.xsd". I will generate a class file "schema.vb" using the following command in command prompt

xsd /d /l:VB C:\schema.xsd /n:XSDSchema.Namespace<?xml
    namespace="" prefix="O" ?>

This will generate a class file in the location where the XSD.exe exists. Copy the file and add it to the class library or the project you use and then you have to assign the columns in each elements of the schema with the values and thus the dataset gets generated. You will not have any idea until you look into the sample code I have attached.

Private Function FillDataset(ByVal ds As DataSet) As String
    Dim _integrationMessage As New IntegrationMessage()
    Dim prevCustomer_id As Integer = -1
    Dim Customer_id As Integer

    'adding the header
    With _integrationMessage.Header
        Dim HeaderRow As IntegrationMessage.HeaderRow
        HeaderRow = .NewHeaderRow()
        With HeaderRow
            .messageType = "xml"
            .sendDate = Date.Now
            .sender = "Odin"
            .Header_Id = 1 'as there will be one header
        End With
        .Rows.Add(HeaderRow)
    End With

    'adding the body information
    With _integrationMessage.Body
        Dim Bodyrow As IntegrationMessage.BodyRow
        Bodyrow = .NewBodyRow()
        With Bodyrow
            .Body_Id = 1 'as there will be one body
        End With
        .Rows.Add(Bodyrow)
    End With

    'adding the body contents from the dataset
    For Each row As DataRow In ds.Tables(0).Rows
        Customer_id = row("Customer_id")

        If prevCustomer_id <> Customer_id Then
            'the customer has changed therefore 
            'new customer nodes to be created

            'adding the students element
            With _integrationMessage.Students
                Dim StudentsRow As IntegrationMessage.StudentsRow
                StudentsRow = .NewStudentsRow()
                With StudentsRow
                    .Body_Id = 1 'as there will be a single body
                    .Students_Id = Customer_id
                End With
                .Rows.Add(StudentsRow)
            End With

            'adding the student element
            With _integrationMessage.Student
                Dim StudentRow As IntegrationMessage.StudentRow
                StudentRow = .NewStudentRow()
                With StudentRow
                    .Students_Id = Customer_id
                    .studentId = Customer_id
                    .errorMessage = ""
                    .errorNumber = -1
                End With
                .Rows.Add(StudentRow)
            End With

            'adding the student info element
            With _integrationMessage.StudentInfo
                Dim StudentInfoRow As IntegrationMessage.StudentInfoRow
                StudentInfoRow = .NewStudentInfoRow()
                With StudentInfoRow
                    .studentId = Customer_id
                    .isActive = IIf(row("Customer_isActive") = 1, True, False)
                    .firstName = row("FirstName")
                    .lastName = row("LastName")
                    .homeCountry = row("HomeCountry")
                    .email = row("Email")
                    .startDate = row("StartDate")
                    .endDate = row("EndDate")
                    .currentLevel = row("CurrentLevel")
                    .bookedDate = row("BookedDate").bookedDate = row("BookedDate")
                    .cancelledDate = row("CancelledDate")
                    .SchoolCode = row("SchoolCode")
                    .programCode = row("ProgramCode")
                    .courseTypeCode = row("CourseTypeCode")
                    .courseIntensityCode = row("CourseIntensityCode")
                    .languageCode = row("LanguageCode")
                    .updateDate = row("CustomerUpdateDate")
                    .RedemptionCode = row("RedemptionCode")
                End With
                .Rows.Add(StudentInfoRow)
            End With
        End If

        'adding the courses which can be multiple for a customer
        With _integrationMessage.Courses
            Dim CoursesRow As IntegrationMessage.CoursesRow
            CoursesRow = .NewCoursesRow()
            With CoursesRow
                .Courses_Id = row("Course_id")
                .studentId = Customer_id
            End With
            .Rows.Add(CoursesRow)
        End With

        'adding the course entity
        With _integrationMessage.Course
            Dim CourseRow As IntegrationMessage.CourseRow
            CourseRow = .NewCourseRow()
            With CourseRow
                .Courses_Id = row("Course_id")
                .courseId = row("Customer_id")
                .isActive = IIf(row("Course_isActive") = 1, True, False)
                .language = row("LanguageCode")
                .SchoolCode = row("SchoolCode")
                .startDate = row("StartDate")
                .updateDate = row("CourseUpdateDate")
            End With
            .Rows.Add(CourseRow)
        End With

        prevCustomer_id = Customer_id
    Next

    Return _integrationMessage.GetXml()

End Function

The above function fills the schema based dataset "IntegrationMessage" with the dataset "ds" which I loaded from SQL. Once you are done with setting all the attributes with the values, you can play around with all the functionalities you can do with the dataset. Interesting! Isn't it?

Note: Having an experience in working with three tier architecture will help you. If you don’t have an experience or an idea of what three tier architecture is, then it will be better you grasp some knowledge on it before you get into coding.

Points of Interest

Found out how bad it is to waste three days keeping the ultimate tool in my desktop.

History

Please do check out my other articles, which may help you out.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

jebarson
Software Developer (Senior) Microsoft Corporation
India India
I work for Microsoft on MS technologies for application development. My interests include .net, WCF, Azure, Windows Phone, ASP.net, SL, WCF, WPF and many more.

You can visit my site at http://www.jebarson.info

Follow me on twitter @jebarson007

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 1 Pin
ednsinf3-Jan-14 1:28
memberednsinf3-Jan-14 1:28 
QuestionHow can i do this in C# Pin
leanthony092713-Sep-12 0:03
memberleanthony092713-Sep-12 0:03 
QuestionChange the element name Pin
darshanadsouza8-Feb-12 20:09
memberdarshanadsouza8-Feb-12 20:09 
General'The same table <element> cannot be the child table in two nested relations' ERROR Pin
Nando_Drummer24-Feb-11 5:36
memberNando_Drummer24-Feb-11 5:36 
GeneralRe: 'The same table cannot be the child table in two nested relations' ERROR Pin
jebarson24-Feb-11 5:41
memberjebarson24-Feb-11 5:41 
GeneralHere's something wich maybe help Pin
Jhimy Fernandes Villar18-Oct-09 12:07
memberJhimy Fernandes Villar18-Oct-09 12:07 
Questionwhat is integration message? Pin
n12prashant31-Oct-08 0:18
membern12prashant31-Oct-08 0:18 
AnswerRe: what is integration message? Pin
jebarson13-Nov-08 3:29
memberjebarson13-Nov-08 3:29 
GeneralXml file generation based on xsd file Pin
kiran_dq6-Aug-07 9:46
memberkiran_dq6-Aug-07 9:46 
QuestionWhere is GetXml method? Pin
Namshub5-Jan-07 3:42
memberNamshub5-Jan-07 3:42 
AnswerRe: Where is GetXml method? Pin
jebarson5-Jan-07 11:19
memberjebarson5-Jan-07 11:19 
GeneralRe: Where is GetXml method? [modified] Pin
Namshub7-Jan-07 22:01
memberNamshub7-Jan-07 22:01 
GeneralRe: Where is GetXml method? Pin
ddecoy12-Jan-10 4:05
memberddecoy12-Jan-10 4:05 
GeneralRe: Where is GetXml method? [modified] Pin
leanthony092713-Sep-12 0:00
memberleanthony092713-Sep-12 0:00 
GeneralSome more Help Pin
HemaRawat4-Jan-07 0:31
memberHemaRawat4-Jan-07 0:31 
GeneralRe: Some more Help Pin
jebarson5-Jan-07 11:16
memberjebarson5-Jan-07 11:16 
Questionwhat are the steps required to be taken after generating dataset class? Pin
garimajain_mca28-Nov-06 20:30
membergarimajain_mca28-Nov-06 20:30 
AnswerRe: what are the steps required to be taken after generating dataset class? Pin
jebarson28-Nov-06 23:47
memberjebarson28-Nov-06 23:47 
GeneralAllready done Pin
Peter Ketelaars23-Oct-06 21:54
memberPeter Ketelaars23-Oct-06 21:54 
GeneralRe: Allready done Pin
jebarson24-Oct-06 21:20
memberjebarson24-Oct-06 21:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150603.1 | Last Updated 16 Oct 2006
Article Copyright 2006 by jebarson
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid