gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:57:28 25 4
gpt4 key购买 nike

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: 我有一个类来保存从数据库返回的数据

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

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 实际上是空的,因为我从代码隐藏中注入(inject) html。

当调用 PersonInfo.aspx 时,将显示在占位符中具有适当值的 html 模板标记。我也有可能想在 html 电子邮件中发送最终标记(尽管这不是问题的一部分,因为我知道如何通过电子邮件发送)。

这是在我的 html 模板中填充值的最佳方式还是其他更好的选择?

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

所以我的第 3 步中的代码将需要 40-50 个 Replace 语句。

如有任何疑问,请随时提出,非常感谢任何意见。

最佳答案

如果您的页面是有效的 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 友好:

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

关于c# - 用 C# 对象属性值替换 html 模板中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5212335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com