XML is great! But most of you who have worked with it probably pull your hair out due to all the navigational problems and code needed to navigate through the xml-structure. Wouldn't it be neat if there was some way to create a .NET class from an xsd-schema and load it up with the contents of a specific xml-structure? Well, guess what, there is, and it is provided by our very good friends in Redmond, WA, Microsoft.
To some of you, this might be yesterday’s news, but for those of you who havn't tried it, you should.
I will try to explain how to do it here. In this example, we'll be basing the .NET class on a InfoPath form. InfoPath is, as you might know, just a front-end to XML, ie. a user friendly way of creating xml-data.
Create you xml-form in any way you like. I won't go into how exactly you do that, but
That will create a schema in the background. To export it to an xsd-file, select “Save as source files…” from the file menu and direct it to a directory of your choice, for instance, “c:\temp”.
Use the file explorer, go to the directory where you just saved the files, and you will find a file with the name of your different data sources followed by the extension “.xsd” in this directory. Remember the name of the xsd-file, let’s call it “source.xsd” in this example.
Then, start up a “Visual Studio 2005 Command Prompt”, go to the directory where you saved the source files, for instance:
Then, using the command xsd you can create the cs-file containing the .NET-class with the following command:
xsd source.xsd /c
This will create a new file called “source.cs”. This is the file that contains the .NET class.
Now open your development project and add the file source.cs to the project. This will now give you access to the .NET class in you project. Open the file and you can see the name of your class, it should be “myFields”.
Now we want to instantiate the class with some xml-data. This is done in the following manner using c#-code.
XmlSerializer serializer = new XmlSerializer(typeof(myFields));
XmlTextReader reader = new XmlTextReader(“c:\XmlInstanceOfSourceXsd.xml”);
myFields fields = (myFields)serializer.Deserialize(reader);
Now, you can access the xml-data using the instance fields of the class myFields.
CRM and SharePoint Consultant