用类属性值替换所有不同的占位符

发布于 2025-02-13 13:43:50 字数 1698 浏览 1 评论 0原文

我有下面的课程

    public class Details
    {
        public string CreatedAt {set;get;)
        public Order Order { get; set; }
        public Customer Customer { get; set; }
     }
    public class Customer
    {
        public string Name { get; set; }
        public CustomerAddress Address { get; set; }
    }

    public class CustomerAddress
    {
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string City { get; set; }
        public string State { get; set; } 
    }

,并且我的HTML文件具有HTML内容,很少有占位符。我正在以下面的方式替换占位符。


  public static string ReplaceStringPlaceHolders(User Details)
        {
                 string MyHTML= File.ReadAllText(@"...Path");
                 //Replacing one by one
                 string newstring= MyHTML.
                .Replace("{created_at}", Details.CreatedAt)
                .Replace("{customer_info.address.line_1}", Details.Customer.Address.Line1)
                .Replace("{customer_info.address.line_2}", Details.Customer.Address.Line2)
                .Replace("{customer_info.address.city}", Details.Customer.Address.City)
                .Replace("{customer_info.address.state}", Details.Customer.Address.State)
                .Replace("{customer_info.address.postal_code}", Details.Customer.Address.PostalCode)
                .Replace("{customer_info.address.country}", Details.Customer.Address.Country)
            return newstring;

        }

但是我不喜欢这种方式,因为我将50多个占位符放入HTML文件中。 有什么方法可以在占位符名称与类属性匹配时替换占位符。

如果可能的话,我正在寻找这样的东西:

MyHTML.replaceifPlaceHolderMatchesWithClassProperties(Label);

请建议。

I have a class as below

    public class Details
    {
        public string CreatedAt {set;get;)
        public Order Order { get; set; }
        public Customer Customer { get; set; }
     }
    public class Customer
    {
        public string Name { get; set; }
        public CustomerAddress Address { get; set; }
    }

    public class CustomerAddress
    {
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string City { get; set; }
        public string State { get; set; } 
    }

and I have HTML file with HTML content and few placeholder. I am replacing placeholders as below.


  public static string ReplaceStringPlaceHolders(User Details)
        {
                 string MyHTML= File.ReadAllText(@"...Path");
                 //Replacing one by one
                 string newstring= MyHTML.
                .Replace("{created_at}", Details.CreatedAt)
                .Replace("{customer_info.address.line_1}", Details.Customer.Address.Line1)
                .Replace("{customer_info.address.line_2}", Details.Customer.Address.Line2)
                .Replace("{customer_info.address.city}", Details.Customer.Address.City)
                .Replace("{customer_info.address.state}", Details.Customer.Address.State)
                .Replace("{customer_info.address.postal_code}", Details.Customer.Address.PostalCode)
                .Replace("{customer_info.address.country}", Details.Customer.Address.Country)
            return newstring;

        }

but I don't like this way as I have put 50+ placeholders in my HTML file.
Is there a way that we can replace the placeholder when the placeholder name matches to class properties.

I am looking for something like this if possible:

MyHTML.replaceifPlaceHolderMatchesWithClassProperties(Label);

Kindly suggest.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空名 2025-02-20 13:43:51

我认为这会帮助您:

string MyHTML = "{PersonId}, {Name}, {Family}, {Age}";
Person p = new Person();
p.PersonId = 0;
p.Name = "hello";
p.Family = "world";
p.Age = 15;
var properties = typeof(Person).GetProperties().ToDictionary(x => x, x => x.GetType().GetProperties());
foreach (var item in properties)
    MyHTML = MyHTML.Replace("{" + item.Key.Name + "}", typeof(Person).GetProperty(item.Key.Name).GetValue(p).ToString());
Console.WriteLine(MyHTML);

输出:0,您好,World,15

i think this will help you:

string MyHTML = "{PersonId}, {Name}, {Family}, {Age}";
Person p = new Person();
p.PersonId = 0;
p.Name = "hello";
p.Family = "world";
p.Age = 15;
var properties = typeof(Person).GetProperties().ToDictionary(x => x, x => x.GetType().GetProperties());
foreach (var item in properties)
    MyHTML = MyHTML.Replace("{" + item.Key.Name + "}", typeof(Person).GetProperty(item.Key.Name).GetValue(p).ToString());
Console.WriteLine(MyHTML);

output: 0, hello, world, 15

挽心 2025-02-20 13:43:50

是的,您可以在 Reflection linq 的帮助下阅读属性:

using System.Linq;
using System.Reflection;

....

private static string TryReadReflectionValue(object data, string name) {
  if (name == null)
    return null;

  foreach (string item in name.Replace("_", "").Trim('{', '}').Split('.')) {
    if (data == null)
      return null;

    var prop = data
      .GetType()
      .GetProperties(BindingFlags.Instance | BindingFlags.Static | 
                     BindingFlags.Public)
      .Where(p => p.Name.Equals(item, StringComparison.OrdinalIgnoreCase))
      .Where(p => p.CanRead)
      .Where(p => p.GetIndexParameters().Length <= 0)
      .FirstOrDefault();

    if (prop == null)
      return null;

    data = prop.GetValue(prop.GetGetMethod().IsStatic ? null : data);
  }

  return data?.ToString();
}

并在正则表达式的帮助下匹配占位符

using System.Text.RegularExpressions;

...

private static string MyReplace(string text, object data) {
  if (text == null)
    return text;  

  return Regex.Replace(
    text,
    @"\{\w._]+\}",
    match => TryReadReflectionValue(data, match.Value) ?? match.Value);
}

用法:

public static string ReplaceStringPlaceHolders(User Details) {
  string MyHTML= File.ReadAllText(@"...Path");

  return MyReplace(text, Details); 
}

我假设在这里我们

  1. 总是 drop _在占位符中,例如{create_at}对应于create> create> createat属性
  2. 我们忽略占位符中的案例{create_at} == {create_at} == {create_at}等。
  3. 所有占位符都在{字母,数字,_,。}中格式

Yes, you can read properties with a help of Reflection and Linq:

using System.Linq;
using System.Reflection;

....

private static string TryReadReflectionValue(object data, string name) {
  if (name == null)
    return null;

  foreach (string item in name.Replace("_", "").Trim('{', '}').Split('.')) {
    if (data == null)
      return null;

    var prop = data
      .GetType()
      .GetProperties(BindingFlags.Instance | BindingFlags.Static | 
                     BindingFlags.Public)
      .Where(p => p.Name.Equals(item, StringComparison.OrdinalIgnoreCase))
      .Where(p => p.CanRead)
      .Where(p => p.GetIndexParameters().Length <= 0)
      .FirstOrDefault();

    if (prop == null)
      return null;

    data = prop.GetValue(prop.GetGetMethod().IsStatic ? null : data);
  }

  return data?.ToString();
}

And match placeholders with a help of regular expressions:

using System.Text.RegularExpressions;

...

private static string MyReplace(string text, object data) {
  if (text == null)
    return text;  

  return Regex.Replace(
    text,
    @"\{\w._]+\}",
    match => TryReadReflectionValue(data, match.Value) ?? match.Value);
}

Usage:

public static string ReplaceStringPlaceHolders(User Details) {
  string MyHTML= File.ReadAllText(@"...Path");

  return MyReplace(text, Details); 
}

Here I assumed that

  1. We always drop _ in placeholders, e.g {created_at} corresponds to CreatedAt property
  2. We ignore case in placeholders: {created_at} == {Created_At} == {CREATED_at} etc.
  3. All placeholders are in {letters,digits,_,.} format
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文