2015-10-23 80 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); 
       } 
      }