【问题标题】:C# String replace XML Tags with other TagsC# String 用其他标签替换 XML 标签
【发布时间】:2015-10-24 06:44:13
【问题描述】:

我正在构建一个聊天解析器,该解析器应该将描述表情的 XML 标记(在字符串中)替换为具有相关表情文件链接的 HTML 图像标记。

聊天文本示例:

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

应改为如下:

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

图片文件的名字都跟对应的“类型”属性一样。

这是我迄今为止尝试过的:

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\" />";
} 

这会在文本末尾添加所有表情符号,但无法将它们放在文本中。

【问题讨论】:

  • 我尝试了几个字符串和正则表达式替换函数
  • 然后贴出你尝试过的和对应的结果
  • var smilies = XElement.Parse(text) .Descendants("ss") .Select(x =&gt; x.Attribute("type").Value); Regex.Replace(text, "&lt;.*?&gt;", String.Empty); foreach (var smily in smilies) { text += "&lt;img src=\"./Emoticons/" + smily + ".png\" /&gt;"; } 这在文本末尾添加了所有表情符号,但无法将它们放入文本中。
  • 考虑将其编辑到您的答案中。我自己帮不了你,但我相信其他人看到你努力后会的。

标签: c# html xml string


【解决方案1】:

试试这个

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);
        }

    }
}

【讨论】:

    【解决方案2】:

    我终于找到了解决办法:

    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);
                    }
                }
    

    【讨论】:

      猜你喜欢
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多