Generate Code From XML Schema: xsd.exe
Posted over 4 years ago on July 31, 2007
xsd.exe is a handy little tool that comes with the .NET SDK (Software Development Kit) that can make life easy when you want to quickly go from an XML input to a strongly-typed .NET object.
If you're starting with an XML file:
1) Open the XML file in Visual Studio
2) From the XML menu click "Create Schema". This will generate a XSD file.
Below is a script that you can put inside a .BAT file to execute xsd with some common parameters. (You can see all possible parameter values by running xsd.exe /?).
set xsdFile="C:\PathToXSD.XSD" set outDirectory="C:\Users\XXXX\Desktop" set xsdExeDir="C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin" rem set language="VB" set language="CS" xsd.exe "%xsdFile%" /c /out:"%outDirectory%" /l:"%language%" pauseAfter you run this script: where ever you set your "outDirectory" path, a new class file will be waiting. Copy this class file into your project. For the purpose of this example, we'll pretend the class generated is called "GeneratedClassFromXSD".
Likely the next thing you will want to do is get data into the generated object: (Make sure you're using "System.Xml" namespace...)
public GeneratedClassFromXSD GetObjectFromXML()
{
var settings = new XmlReaderSettings();
var obj = new GeneratedClassFromXSD();
var reader = XmlReader.Create(urlToService, settings);
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(GeneratedClassFromXSD));
obj = (GeneratedClassFromXSD)serializer.Deserialize(reader);
reader.Close();
return obj;
}
Edit 08/15/2007:
If your XSD is importing a namespace that is contained in a different XSD file, you must add the second xsd to the command line.
For instance....if the xsd contains something like this:
xs:import namespace="ErrorSchema:0706" schemaLocation="http://localhost/0706/ErrorSchema.xsd"/>
...you must include "ErrorSchema" in the command line like this:
xsd.exe "%xsdFile%" "/pathToImportedSchema.xsd
This took me some time to figure out because I thought that xsd.exe would automatically go out and grab the file from the "schemaLocation" attribute (as it does do with
Add tag: Gotchya!
Comments
SuperSantos writes...
Thanks, it worked perfectly!
March 20, 2009
New Comment