2015-10-23 82 views
0

我正在構建一個聊天分析器,應該用一個鏈接到相關表情符號文件的HTML圖像標籤替換XML標籤(字符串中)來描述表情符號。C#字符串替換XML標籤與其他標籤

舉例聊天文字:

Hi there <ss type="tongueout">:p</ss><ss type="laugh">:D</ss> 

應改爲如下:

Hi there <img src="./Emoticons/toungeout.png" /><img src="./Emoticons/laugh.png" /> 

圖像文件都命名方式與相應的 「類型」 -attribute。

這是我迄今爲止嘗試:

var smilies = XElement.Parse(text) 
         .Descendants("ss") 
         .Select(x => x.Attribute("type").Value); 

Regex.Replace(text, "<.*?>", String.Empty); 
foreach (var smily in smilies) 
{ 
    text += "<img src=\"./Emoticons/" + smily + ".png\" />"; 
} 

這添加的所有表情符號在文本的末尾,但不能夠把他們的文本中的。

+0

我試了幾個與字符串,並正則表達式替換功能 –

+1

然後上傳你已經嘗試什麼,相應的結果 – kskyriacou

+0

'變種笑臉= XElement.Parse(text) .descendants(「ss」) .Select(x => x.Attribute(「type」)。Value); Regex.Replace(text,「<.*?>」,String.Empty); foreach(var smily in smilies) { text + =「」; }' 這增加了文本末尾的所有表情符號,但不能將它們放在文本中。 –

回答

0

試試這個

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 
using System.Globalization; 


namespace ConsoleApplication53 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string xml = 
       "<Root>" + 
        "<ss type=\"tongueout\">:p</ss><ss type=\"laugh\">:D</ss>" + 
       "</Root>"; 

      XElement root = XElement.Parse(xml); 

      XElement[] img = new XElement[] { 
        new XElement("img", new XAttribute("src","./Emoticons/toungeout.png")), 
        new XElement("img", new XAttribute("src", "./Emoticons/laugh.png")) 
      }; 

      XElement ss = root.Element("ss"); 
      ss.ReplaceWith(img); 
     } 

    } 
} 
0

我終於找到了一個解決方案:

string[] split = Regex.Split(text, "</ss>"); 

      text = ""; 

      foreach (string s in split) 
      { 
       Regex regex = new Regex(@"(?<=\btype="")[^""]*"); 
       string smily = regex.Match(s).Value; 

       string result = Regex.Replace(s, @"<(.|\n)*?>", string.Empty); 
       writer.WriteEncodedText(result); 

       if (smily != string.Empty) 
       { 
        writer.AddAttribute(HtmlTextWriterAttribute.Src, "./Emoticons/" + smily + ".png"); 
        writer.RenderBeginTag(HtmlTextWriterTag.Img); 
       } 
      }