CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2007

    How to convert XML file in to a class file using c#?

    Microsoft visual studio 2008

  2. #2
    Join Date
    Jul 2003

    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.

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004

    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)


    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:

    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

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

By using this site, you agree to the Privacy Policy