繁体   English   中英

使用带有占位符的模板在C#中创建XML

[英]Creating XML in C# using templates with placeholders

我需要编写各种类以将XML分发给客户端系统。

我知道在c#中转换类的明显方法是序列化。 理想情况下,我会这样做-但是老板希望我使用某种模板系统。

因此,我将拥有一个类似于以下内容的模板(基本示例),并根据需要替换标签。

<Advert>
<Title>{Title}</Title>
<Description>{Description}</Description>
[etc etc etc etc]
</Advert>

我真的不想这样做,但这就是生活:)有人对如何做到这一点有好的建议吗? 图书馆等? 希望有比字符串替换(等)更强大的功能-但感觉就是这样!

编辑:

我应该说的是,这个想法是能够调整XML模板而不必重新构建应用程序。

我会这样

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

看一看XDocument 如果我正确地阅读了您的问题,则可以执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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