2010
01.21

XElement/XDocument Code Generator

I’ve created an XSLT that when supplied with an XML, creates the corresponding .cs file that would create that specific XML (Confused yet?).  For example, if you have the following XML:


<data format="text">
  <internal-data format="integer">123</internal-data>
  <payload>The quick brown fox jumps over the lazy dog</payload>
</data>

The XSLT result will be:

var doc = new XDocument(
  new XElement("data",
    new XAttribute("format", "text"),
    new XElement("internal-data",
      new XAttribute("format", "integer"),
      new XText(@"123")
    ),
    new XElement("payload",
      new XText(@"The quick brown fox jumps over the lazy dog")
    )
  )
);

You can now use the generated code in a method or unit test. Of course, the example is stupid simple; you can probably hand-code it faster. The XSLT only becomes useful when the XML becomes a bit more intricate that it requires more than 10 minutes to hand-code.

Simple enough, yes? A knowledge of XSLT would, of course, is needed to understand what the XSLT does, but for somebody who just wants a code generator, all you need is an XSLT engine (like Visual Studio 2008).

One limitation of the XSLT is that it can only deal with ONE XML Namespace…so multiple namespaces will need a bit more work on the final generated C# file before it becomes useable.

Trivia: This was supposed to be the topic of my third CodeProject article which I ended up deleting…because the good people at CodeProject thought it “lacks substance” Which I thought was a bit painted with hypocrisy when a huge number of articles in CP have no substance at all. OH, WELL.

Download the XSLT.

No Comment.

Add Your Comment

Spam Protection by WP-SpamFree