2011-05-03 40 views
1

感謝您的閱讀。我正在嘗試寫一點解析器。我想要做的是以下。該數據庫包含3個表格。一個帶有Person(姓名,姓氏,年齡),一個帶有TextTemplates(「此文檔屬於」),另一個帶有TemplateElements(例如...)。所以用戶可以選擇一個TextTemplate,編輯它並添加更多的TemplateElements。當他按下按鈕時,系統應該生成PDF文檔,方法是將TemplateElements替換爲Persons表中人員的相應屬性。問題是獲取與TemplateElement匹配的個人屬性。當然我可以寫一些:.net動態文本解析器

foreach(element...){  
    if(element.Equals("<Name>")) 
     text.Replace("<Name>", Person.Name); 
    if(element.Equals("<LastName>")) 
     text.Replace("<LastName>", Person.LastName); 
} 

但我想保持這個儘可能動態。屬性和TemplateElements將來可能會發生變化。所以最好的解決方案是以某種方式根據實際元素獲取相應的屬性。

如果你們其中一人有解決方案,這將是非常好的。

感謝;)

回答

1

看一看這些博客文章,其中 '命名格式化' 的一些實施討論:

從本質上講,這個想法是你在string上定義了一個擴展方法,它允許你基於語法l來格式化一個字符串IKE {PropertyName}

例子:

Person person = GetPerson(); 
string text = "Hello, {Name} {LastName}"; 
var evaluated = text.FormatWith(person); 
+0

非常感謝。我真的不知道要搜索什麼或如何解決這個問題。謝謝你的協助。 – benjamin 2011-05-03 15:39:58

+0

@benjamin如果這回答你的問題,你可能想'接受'它 – jeroenh 2011-05-03 15:43:48

0

因此,這裏是我的結果是不正是我需要做的;)

private string ReplaceTemplateElements(Person person, string inputText) 
    { 
     //RegExp to get everything like <Name>, <LastName>... 
     Regex regExp = new Regex(@"\<(\w*?)\>", RegexOptions.Compiled); 
     //Saves properties and values of the person object 
     Dictionary<string, string> templateElements = new Dictionary<string, string>(); 
     FieldInfo[] fieldInfo; 
     Type type = typeof(Person); 

     fieldInfo = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); 
     //Putting every property and value in the dictionary 
     foreach (FieldInfo info in fieldInfo) 
     { 
      templateElements.Add(info.Name.TrimStart('_'), info.GetValue(person).ToString()); 
     } 

     //Replacing the matching templateElements with the persons properties 
     string result = regExp.Replace(inputText, delegate(Match match) 
     { 
      string key = match.Groups[1].Value; 
      return templateElements[key]; 
     }); 
     return result; 
    } 

所以用這個,我沒有在意屬性的人。添加或刪除屬性不會影響此方法的功能。它只是在inputText中查找現有的templateElement,並用Persons-Object的匹配屬性(如果存在匹配的屬性)替換它們)。如果有任何建議,請告訴我。