Microsoft visual studio 2008
Printable View
Microsoft visual studio 2008
XML Serialization is the easiest way but if this is a hand made XML file (and no class created to go along with it) then I think you're stuck doing it by hand and coding the class first.
The quick way is to use tools such as xsd.exe or XsdObjectGen.exe.
These tools allow you to quickly generate C# or VB classes from an xsd file.
Here's what to do:
1) Open an xml file in Visual Studio
2) Create an xsd schema. ('XML\Create Schema')
3) If necessary, edit the schema file
4) Open a Visual Studio command window and run one of the tools
5) Edit the generate classes (if necessary)
Example:
The above command will generate a MyXmlClass.cs file that you include in your project.Code:C:\projects\myproject\xsd.exe MyXmlClass.xsd /classes /n:CG.MyNamespace
To load up the class, it's as easy as:
Saving data from the class back to an Xml file is equally as easy.Code:XmlSerializer serializer = new XmlSerializer( typeof( MyXmlClass ) );
using( XmlReader reader = XmlReader.Create( file ) )
{
MyXmlClass myXmlClass = ( MyXmlClass )serializer.Deserialize( reader );
}
NOTE: Feel free to hand edit the generated files (but understand if you regenerate them, your changes will be lost). I generally use the xsd.exe tool first and then hand edit. Xsd.exe will generate any collections using raw arrays (e.g. myField[]) which I don't like to use because users of the class need to always check for null in order to loop the items. So I hand edit and replace these arrays with generic List<>'s.