c#字符串用其他标签替换XML标签
本文关键字:标签 替换 XML 其他 字符串 | 更新日期: 2023-09-27 18:18:57
我正在构建一个聊天解析器,它应该用HTML图像标记替换描述具有链接到相关表情符号文件的表情符号的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" />
所有的图像文件都以相应的"type"属性命名。
以下是我到目前为止所做的尝试:
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'" />";
}
这将在文本末尾添加所有的符号,但不能将它们放在文本中。
试试这个
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);
}
}
}
我终于找到了解决办法:
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);
}
}