Reputation: 116
I have various classes that I need to write to XML for distribution to client systems.
I know the obvious way to convert a class in c# is to serialize. Ideally I would do this - however my boss wants me to use some sort of template system.
So I would have a template (basic example) like the following and replace the tags as required.
<Advert>
<Title>{Title}</Title>
<Description>{Description}</Description>
[etc etc etc etc]
</Advert>
I really don't want to do it this way, but that's life :) Does anyone have good suggestions on how to do this? Libraries etc? Hoping there is something a bit more powerful then string replace (etc) - but got a feeling that's the way it may go!
EDIT:
What I should have stated is, the idea is to be able to tweak the XML template without having to do a rebuild of the application.
Upvotes: 1
Views: 2049
Reputation: 50712
I would do it like this
var parameters = new Dictionary<string, string>
{
{"Title", "Hello"},
{"Description", "Descr1"}
};
string xml = "<Advert><Title>{Title}</Title><Description>{Description}</Description></Advert>";
var replaced = Regex.Replace(xml, @"\{(.+?)\}", m => parameters[m.Groups[1].Value]);
Upvotes: 2
Reputation: 1304
Take a look at XDocument. If I'm reading your question right, you could do:
// Set these however you want
string title = "{Title}"
string description = "{Description}"
XDocument xml = new XDocument(
new XElement("Advert",
new XElement("Title", title),
new XElement("Description", description)
... ));
Upvotes: 1