C# Class (source code) Generator from XML file

11,063

Solution 1

There is a built-in way to do this in VS2008 and later, T4. Hanselman has a bunch of great links in one place.

Solution 2

How about Xsd2Code: http://xsd2code.codeplex.com/

Share:
11,063
Nate
Author by

Nate

Dad. Geek. Gamer. Web developer. Cloud user. Old Car enthusiast. Blogger.

Updated on June 29, 2022

Comments

  • Nate
    Nate almost 2 years

    What tools have you used to create class source code from xml files? Is this an edge case that I need to roll my own? I have need to create DTOs from some XML files, but the XML files are subject to change (add/remove attributes) so I need to be able to quickly update them.

    I'm reallly not impressed with the .xml -> .xsd -> bloated .cs approach, and was looking for something to hopefully generate simple POCOs for me. Are there any tools you've used or seen that do this?

  • code4life
    code4life almost 14 years
    T4 reminds me sooo much of Apache Velocity... there's a .NET port called NVelocity by the way. T4 is much better integrated to VS, than NVelocity, so probably worth looking into. Also nice to see that it's not restricted to sheerly .cs, but supports any other text format...
  • Nate
    Nate almost 14 years
    Is there a way I can use an existing class from within the T4 template? I'm getting an error "The type or namespace name 'myclass' could not be found." I have added it as a reference to the project the T4 template is in, am I doning something wrong?
  • blowdart
    blowdart almost 14 years
    Nope, you have to start by writing the code to do the transformation, because it's a general engine, not just for xml and xslt
  • Nate
    Nate almost 14 years
    No, I have a T4 style for loop that generates the code I want on a hard coded list, I have a class that can return a list of data from my XML file, I Just can't figure out how to initialize my class in the T4 template. I've seen other people use framework base classes syetem.io.file for instance.
  • Nate
    Nate almost 14 years
    I ended up needing the <#@ assembly name="PathToDll"> tag at the top of my file and it works great!