June 14, 2003

XML and C#

At work, we've been trying to use XML for our configuration files. Writing the XML files, and even the XML schema, has been pretty easy. Writing the pages of code to call MSXML from C++ to parse the files has been relatively simple, but still tedious. It is, after all, still pages of code to get all the properties you want out of a reasonably complex XML document.

Then I found out how to do it with C# and .NET. It's incredibly easy. Visual Studio .NET includes a command-line tool (xsd.exe) to convert an XML schema file to a C# data structure. The data structure is tagged with all sorts of attributes so that .NET can later know how to map the XML into that structure. So, from a schema file foo.xsd, you run:

   xsd /c foo.xsd

which creates foo.cs, containing the data structures defined by your schema.

Then, to fill in the data structure, you call the XMLSerializer to 'deserialize' the XML into your data structure:

TextReader myStreamReader = new StreamReader(@"c:\dev\foo.xml");

XmlSerializer serializer = new XmlSerializer(typeof(ConfigType));
ConfigType config;
try
{
   config = (ConfigType)serializer.Deserialize(myStreamReader);
}
catch(XmlException xe)
{
   MessageBox.Show (xe.Message, "XML Parse Error",
      MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch(InvalidOperationException ioe)
{
   MessageBox.Show (ioe.InnerException.Message, "XML Serialization Error",
      MessageBoxButtons.OK, MessageBoxIcon.Error);
}

And that's it. The exception handling is just so that you can figure out what the problem is should the XML file not parse. Assuming you didn't get an exception, your data structure (config) is completely filled in. To see what was set in the XML file, you just look at the fields in the data structure.

Posted by Mike at June 14, 2003 10:26 AM