|
-
December 19th, 2007, 02:24 AM
#1
How to convert XML file in to a class file using c#?
Microsoft visual studio 2008
-
December 19th, 2007, 08:25 AM
#2
Re: How to convert XML file in to a class file using c#?
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.
-
December 19th, 2007, 01:38 PM
#3
Re: How to convert XML file in to a class file using c#?
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:
Code:
C:\projects\myproject\xsd.exe MyXmlClass.xsd /classes /n:CG.MyNamespace
The above command will generate a MyXmlClass.cs file that you include in your project.
To load up the class, it's as easy as:
Code:
XmlSerializer serializer = new XmlSerializer( typeof( MyXmlClass ) );
using( XmlReader reader = XmlReader.Create( file ) )
{
MyXmlClass myXmlClass = ( MyXmlClass )serializer.Deserialize( reader );
}
Saving data from the class back to an Xml file is equally as easy.
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|