views:

223

answers:

3

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?

+3  A: 

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

blowdart
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...
code4life
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?
Nate Bross
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
blowdart
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 Bross
I ended up needing the `<#@ assembly name="PathToDll">` tag at the top of my file and it works great!
Nate Bross
+1  A: 

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

code4life
this is sweat - thanks for the link
Doug
A: 

T4 sounds perfect for this.

It's essentially an ASP.NET like syntax to generate code based on your template.

You would write the template to output the code for the POCO as needed, and then embed code in the template to iterate over your XML collection.

T4 is part of Visual Studio 2008 (but undocumented), and 2010. The Microsoft DSL tools gives support for T4 for Visual Studio 2005 as a separate download.

http://msdn.microsoft.com/en-us/library/bb126445.aspx

Kilanash