字符串替换为列表字典数据不磨损
本文关键字:数据 不磨损 字典 列表 替换 字符串 | 更新日期: 2023-09-27 18:33:59
我试图用ListDictionary中的值替换html中的标记键。但它并没有按照我的预期工作。谁能给我一个解决方案。
我的替换方法
public static string GetDataAddedTemplate(string htmlTemplate, ListDictionary replacements)
{
foreach (DictionaryEntry item in replacements)
{
htmlTemplate.Replace(item.Key.ToString().ToLower(), item.Value.ToString());
}
return htmlTemplate;
}
我的 html 模板就像 folows 一样
<html>
<body>
<table align="left" border="0">
<tr>
<td>
<table align="left" border="1" cellpadding="1" cellspacing="1" style="width: 200px;">
<thead>
<tr style="text-align:center">
<th>Bill To</th>
</tr>
</thead>
<tbody>
<tr style="text-align:center">
<td>
<<username>>
<br />
<br />
<br />
<br />
<br />
</td>
</tr>
</tbody>
</table>
</td>
<td>
<table align="left" border="1" cellpadding="1" cellspacing="1">
<thead>
<tr style="text-align:center">
<th colspan="2">Payment information</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Date
</td>
<td><<createddate>></td>
</tr>
<tr>
<td>Card holder</td>
<td><<cardname>></td>
</tr>
<tr>
<td>Card</td>
<td><<cardbrand>> ############<<cardnumber>></td>
</tr>
<tr>
<td>Amount paid</td>
<td>$<<amountpaid>></td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p>
Congratulations! You've successfully purchased the <<shares>> plan.
</p>
<table align="left" border="1" cellpadding="1" cellspacing="1" style="width: 500px;">
<thead>
<tr style="text-align:center">
<th>Qty</th>
<th>Plan</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr style="text-align:center">
<td>1</td>
<td><<shares>> Plan</td>
<td></td>
<td>$<<amountpaid>></td>
</tr>
</tbody>
</table>
<p> </p>
<p> </p>
<p>
<strong>Thank You</strong>!<br />
Your business is appreciated
</p>
<p> </p>
<p>Team</p>
</body>
</html>
And my ListDictionary is as follows
ListDictionary replacements = new ListDictionary
{
{ "<<UserName>>", "DisplayName" },
{ "<<CardName>>", "Name" },
{ "<<CardNumber>>", "Last4" },
{ "<<CardBrand>>", "Brand" },
{ "<<AmountPaid>>", "Amount" },
{ "<<CreatedDate>>", "chargeDetails" },
{ "<<Shares>>", "shares" }
};
string
是不可变的。因此,调用 String.Replace
会返回一个新字符串,并且不会更改现有字符串。
您需要使用返回的字符串:
public static string GetDataAddedTemplate(string htmlTemplate, ListDictionary replacements)
{
foreach (DictionaryEntry item in replacements)
{
// Use the string returned by Replace method
htmlTemplate = htmlTemplate.Replace(item.Key.ToString().ToLower(), item.Value.ToString());
}
return htmlTemplate;
}
试试这个:
foreach (DictionaryEntry item in replacements)
{
htmlTemplate = htmlTemplate.Replace(item.Key.ToString().ToLower(), item.Value.ToString());
}