简体   繁体   中英

Creating XML in C# using templates with placeholders

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.

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]);

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)
        ... ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM