I have some XML in the following schema:
<Form ID="1" Formtitle="Title">
<Fields>
<Fieldset Legend="LegendText" >
<Field FieldName="Field1" Label="Title" Type="Text" Required="1" />
<Field FieldName="Field2" Label="Radio" Type="Radio" Required="0">
<Option Value="1" Text="Just One"/>
<Option Value="2" Text="Maybe Two"/>
</Field>
</Fieldset>
</Fields>
</Form>
I need to parse through this in C# to generate a HTML form that would represent the following:
<h1>Formtitle</h1>
<form id="1" action="myurl.com">
<fieldset>
<legend>LegendText</legend>
<label>Title</label>
<input type="text" name="Field1" class="jqueryValidate"/>
<!-- jqueryvalidate class added as required is equal to 1 in XML -->
<label>Radio</label>
<input type="radio" name="Field2" Value="1"/> Just One
<input type="radio" name="Field2" Value="2"/> Maybe Two
</fieldset>
</form>
Now, I am aware that I can achieve the same kind of thing using XSLT, however I must use C# here as I will be wrapping this up into a control that I can drop in to any of my pages.
My question is, how could I acheive something like this? I envisage it requiring some type of nested switch statements to check node names and types etc, and stringbuilding the HTML. But, I’m hoping this isn’t the case, and you boffins can help point me in the right direction with this.
Thanks in advance 🙂
Dave
One way to achieve this would be to devise some objects that represent the various HTML entities that you want to generate. Note, this is a very, very simplified example. You could have a base class with all kinds of trickery and reusability in it. But that’s out of the scope of the question and we’d both be here all day 🙂
Obviously, you’d have an
Elementderived class for each HTML element. We also have a way of having them initialised from an Xml node. But now, we need to associate our Xml tags with our DOM objects. We can do that using a dictionary (in this simple case. I’d prefer a full blown factory, but again – that’s outside the scope of this answer!)I’ll go ahead and add the one for our
FieldSetelement:Ok! We’re almost there. Next step is to to translate that XML document in to objects. I’ll presume at this point we’d have some kind of a root object. I’m going to call that
Html(surprising name!). As you can guess, it also derives fromElement. It’s going to act as our root node.Now, we’ll need a function to read the Xml in and translate it in to our current parent.
Wow! We’re practically done. At this point, we have a collection of objects! All that remains is to render them.
BAM. We’re done.
Sorry if there are any errors in the code, I’ll try and go over it. I have not run this, but I have done something similar before. I’m also not suggesting this is the best way, I am sure there are others. This is one way. I’ve left out the rendering of attributes for reasons of brevity, but I’ll be happy to add another concrete
Elementexample to show how that might work.