用C#对象属性值替换html模板中的项目

时间:2020-12-14 21:32:50

1: I have a .html file that has some markup with some placeholder tags.

1:我有一个.html文件,其中包含一些带有一些占位符标记的标记。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
   First Name : <FIRSTNAME/>   <br />
   Last Name:  <LASTNAME/>
</body>
</html>

2: I have a Class to hold data returned from db

2:我有一个Class来保存从db返回的数据

public class Person
{
    public Person()
    {
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

3: PersonInfo.aspx I write out this .html with the placeholder replaced by actual values.

3:PersonInfo.aspx我写出这个.html,占位符替换为实际值。

public partial class PersonInfo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Person per= new Person();
        per.FirstName = "Hello";
        per.LastName = "World";

        string temp = File.ReadAllText(Server.MapPath("~/template.htm"));
        temp = temp.Replace("<FIRSTNAME/>", per.FirstName);
        temp = temp.Replace("<LASTNAME/>", per.LastName);
        Response.Write(temp);
    }
}

4: PersonInfo.aspx is literally empty since I am injecting html from code-behind.

4:PersonInfo.aspx实际上是空的,因为我从代码隐藏中注入了html。

When the PersonInfo.aspx is called the html-template markup with appropriate values in the placeholder will be displayed. Also there are chances I would like to send the final markup in an html email (though that is not part of the question as I know how to email).

调用PersonInfo.aspx时,将显示带有占位符中适当值的html-template标记。还有机会我想在html电子邮件中发送最终标记(虽然这不是问题的一部分,因为我知道如何发送电子邮件)。

Is this the best way to fill values in my html-template or is the any other better alternative?

这是填写我的html模板中值的最佳方法,还是其他更好的选择?

Note: This is a very simple sample example. My class is very complex involving objects as properties and also my html template have 40-50 placeholders.

注意:这是一个非常简单的示例示例。我的类非常复杂,涉及对象作为属性,我的html模板也有40-50个占位符。

So code in my step 3 will need 40-50 Replace statements.

因此,我的第3步中的代码将需要40-50个替换语句。

Feel free to ask if any doubts and really appreciate any inputs.

随意询问是否有任何疑问,并非常感谢任何输入。

4 个解决方案

#1


1  

I would change your page to use an xslt. This is a really easy way to do replacing of things from the database. The only work you'd have to do then is make your XML document with the data from your database.

我会改变你的页面使用xslt。这是从数据库中替换事物的一种非常简单的方法。您需要做的唯一工作就是使用数据库中的数据制作XML文档。

#2


3  

If your page is valid XML (as I'm guessing it is based on the example), then you could parse it into an XElement and do a descendant search by node name. You can probably write a more efficient version, but an example would be:

如果您的页面是有效的XML(因为我猜它是基于该示例),那么您可以将其解析为XElement并按节点名称执行后代搜索。你可以写一个更有效的版本,但一个例子是:

.NET 3.5

    public void Page_Load(object sender, EventArgs e)
    {
        Person person = new Person { FirstName = "Hello", LastName = "World" };
        var dictionary = typeof(Person).GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .ToDictionary(p => p.Name.ToUpperInvariant(), p => (p.GetValue(person, null) ?? string.Empty).ToString());
        var xe = XElement.Parse(File.ReadAllText(HttpContext.Current.Server.MapPath("~/template.htm")));
        foreach (var key in dictionary.Keys)
        {
            foreach (var match in xe.Descendants(key))
            {
                match.ReplaceAll(dictionary[key]);
            }
        }
    }

.NET 2.0 Friendly:

        var person = new Person();
        person.FirstName = "Hello"; 
        person.LastName = "World";
        var dictionary = new Dictionary<string, string>();
        foreach(var propertyInfo in typeof(Person).GetProperties(BindingFlags.Public|BindingFlags.Instance))
        {
            var elementName = propertyInfo.Name.ToUpperInvariant();
            var value = (propertyInfo.GetValue(person, null) ?? string.Empty).ToString();
            dictionary.Add(elementName,value);
        }
        var xml = new XmlDocument();
        xml.LoadXml(File.ReadAllText(HttpContext.Current.Server.MapPath("~/template.htm")));
        foreach(var key in dictionary.Keys)
        {
            var matches = xml.GetElementsByTagName(key);
            for(int i = 0; i<matches.Count;i++)
            {
                var match = matches[i];
                var textNode = xml.CreateTextNode(dictionary[key]);
                match.ParentNode.ReplaceChild(textNode, match);
            }
        }

#3


1  

I would use an SqlDataSource and a Repeater control. They make it very easy to pull your data from the database, and then display it on the page. You wouldn't need to do any code-behind as everything would be handled for you by .NET.

我会使用SqlDataSource和Repeater控件。它们使您可以非常轻松地从数据库中提取数据,然后将其显示在页面上。您不需要执行任何代码隐藏,因为.NET将为您处理所有内容。

Your data source would look something like this:

您的数据源看起来像这样:

<asp:sqlDataSource ID="mySqlDataSource" SelectCommand="SELECT firstName, lastName FROM tablename" />

And then you need a control that can use the returned data and display it on the page:

然后你需要一个可以使用返回数据并在页面上显示它的控件:

<asp:Repeater runat="server">
    <HeaderTemplate>
        <table>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td>First Name: <%#Container.DataItem("firstName")%>"</td>
        </tr>
        <tr>
            <td>Last Name: <%#Container.DataItem("lastName")%></td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>

Edit:

编辑:

Since you don't want to use a datasource and a databound control, I would recommend the XmlTextWriter class. There is a very good tutorial here. This would allow you to be more flexible than if you were reading the template from a separate HTML file.

由于您不想使用数据源和数据绑定控件,我建议使用XmlTextWriter类。这里有一个非常好的教程。这将使您比从单独的HTML文件中读取模板更灵活。

#4


1  

Since you are generating an email consider using MailDefinition.CreateMailMessage. You will have to copy the placeholders and replacement values to a Dictionary object.

由于您要生成电子邮件,请考虑使用MailDefinition.CreateMailMessage。您必须将占位符和替换值复制到Dictionary对象。

#1


1  

I would change your page to use an xslt. This is a really easy way to do replacing of things from the database. The only work you'd have to do then is make your XML document with the data from your database.

我会改变你的页面使用xslt。这是从数据库中替换事物的一种非常简单的方法。您需要做的唯一工作就是使用数据库中的数据制作XML文档。

#2


3  

If your page is valid XML (as I'm guessing it is based on the example), then you could parse it into an XElement and do a descendant search by node name. You can probably write a more efficient version, but an example would be:

如果您的页面是有效的XML(因为我猜它是基于该示例),那么您可以将其解析为XElement并按节点名称执行后代搜索。你可以写一个更有效的版本,但一个例子是:

.NET 3.5

    public void Page_Load(object sender, EventArgs e)
    {
        Person person = new Person { FirstName = "Hello", LastName = "World" };
        var dictionary = typeof(Person).GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .ToDictionary(p => p.Name.ToUpperInvariant(), p => (p.GetValue(person, null) ?? string.Empty).ToString());
        var xe = XElement.Parse(File.ReadAllText(HttpContext.Current.Server.MapPath("~/template.htm")));
        foreach (var key in dictionary.Keys)
        {
            foreach (var match in xe.Descendants(key))
            {
                match.ReplaceAll(dictionary[key]);
            }
        }
    }

.NET 2.0 Friendly:

        var person = new Person();
        person.FirstName = "Hello"; 
        person.LastName = "World";
        var dictionary = new Dictionary<string, string>();
        foreach(var propertyInfo in typeof(Person).GetProperties(BindingFlags.Public|BindingFlags.Instance))
        {
            var elementName = propertyInfo.Name.ToUpperInvariant();
            var value = (propertyInfo.GetValue(person, null) ?? string.Empty).ToString();
            dictionary.Add(elementName,value);
        }
        var xml = new XmlDocument();
        xml.LoadXml(File.ReadAllText(HttpContext.Current.Server.MapPath("~/template.htm")));
        foreach(var key in dictionary.Keys)
        {
            var matches = xml.GetElementsByTagName(key);
            for(int i = 0; i<matches.Count;i++)
            {
                var match = matches[i];
                var textNode = xml.CreateTextNode(dictionary[key]);
                match.ParentNode.ReplaceChild(textNode, match);
            }
        }

#3


1  

I would use an SqlDataSource and a Repeater control. They make it very easy to pull your data from the database, and then display it on the page. You wouldn't need to do any code-behind as everything would be handled for you by .NET.

我会使用SqlDataSource和Repeater控件。它们使您可以非常轻松地从数据库中提取数据,然后将其显示在页面上。您不需要执行任何代码隐藏,因为.NET将为您处理所有内容。

Your data source would look something like this:

您的数据源看起来像这样:

<asp:sqlDataSource ID="mySqlDataSource" SelectCommand="SELECT firstName, lastName FROM tablename" />

And then you need a control that can use the returned data and display it on the page:

然后你需要一个可以使用返回数据并在页面上显示它的控件:

<asp:Repeater runat="server">
    <HeaderTemplate>
        <table>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td>First Name: <%#Container.DataItem("firstName")%>"</td>
        </tr>
        <tr>
            <td>Last Name: <%#Container.DataItem("lastName")%></td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>

Edit:

编辑:

Since you don't want to use a datasource and a databound control, I would recommend the XmlTextWriter class. There is a very good tutorial here. This would allow you to be more flexible than if you were reading the template from a separate HTML file.

由于您不想使用数据源和数据绑定控件,我建议使用XmlTextWriter类。这里有一个非常好的教程。这将使您比从单独的HTML文件中读取模板更灵活。

#4


1  

Since you are generating an email consider using MailDefinition.CreateMailMessage. You will have to copy the placeholders and replacement values to a Dictionary object.

由于您要生成电子邮件,请考虑使用MailDefinition.CreateMailMessage。您必须将占位符和替换值复制到Dictionary对象。