如何拆分HTML字符串,同时保留内容顺序和对应的HTML元素类型
需求说明
将HTML字符串拆分为键值对结构,同时保留文本内容和对应所属的HTML元素类型。
示例
输入
var input = "This is <b>bold</b> where as <i>this is italic</i>. This is the last sentence";
期望输出
{"This is ", "None"}, {"bold", "Bold"}, {" where as ", "None"}, {"this is italic", "Italic"}, {". This is the last sentence", "None"},
原有代码问题
原有实现存在以下缺陷:
- 硬编码逐个标签拆分,新增标签需要修改代码,可扩展性极差
- 拆分逻辑仅拆分文本,没有对应记录每个文本所属的标签类型
- Split方法返回值类型不匹配,无法正常运行
- 返回的Dictionary未做任何数据填充,直接返回空结果
正确实现方案
注意:C# 原生普通Dictionary不保证插入顺序,如果你需要结果顺序和原文本一致,更推荐使用List<KeyValuePair<string, string>>作为返回值,以下是无第三方依赖的实现代码:
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Linq; internal List<KeyValuePair<string, string>> SplitTextByHtmlTags(string input) { var result = new List<KeyValuePair<string, string>>(); // 匹配所有开闭HTML标签 var tagRegex = new Regex(@"<(/?)(\w+)>", RegexOptions.Compiled); var currentTagStack = new Stack<string>(); int lastTextEndIndex = 0; foreach (Match match in tagRegex.Matches(input)) { // 先存入当前标签前的文本片段 if (match.Index > lastTextEndIndex) { string text = input.Substring(lastTextEndIndex, match.Index - lastTextEndIndex); string tagType = currentTagStack.Count > 0 ? CapitalizeFirstLetter(currentTagStack.Peek()) : "None"; result.Add(new KeyValuePair<string, string>(text, tagType)); } bool isClosingTag = !string.IsNullOrEmpty(match.Groups[1].Value); string tagName = match.Groups[2].Value.ToLower(); if (isClosingTag) { // 匹配到闭标签,弹出栈顶对应标签 if (currentTagStack.Count > 0 && currentTagStack.Peek() == tagName) { currentTagStack.Pop(); } } else { // 匹配到开标签,压入栈 currentTagStack.Push(tagName); } lastTextEndIndex = match.Index + match.Length; } // 存入最后一段无后续标签的文本 if (lastTextEndIndex < input.Length) { string text = input.Substring(lastTextEndIndex); string tagType = currentTagStack.Count > 0 ? CapitalizeFirstLetter(currentTagStack.Peek()) : "None"; result.Add(new KeyValuePair<string, string>(text, tagType)); } return result; } // 辅助方法:将标签名转为首字母大写格式,匹配期望输出规则 private string CapitalizeFirstLetter(string rawTag) { if (string.IsNullOrWhiteSpace(rawTag)) return rawTag; return char.ToUpper(rawTag[0]) + rawTag.Substring(1).ToLower(); }
如果必须返回Dictionary结构,可基于上述方法的结果转换,前提是文本片段无重复:
internal Dictionary<string, string> SplitTextByHtmlTagsToDict(string input) { return SplitTextByHtmlTags(input).ToDictionary(kv => kv.Key, kv => kv.Value); }
该实现支持所有合法行内HTML标签,自动适配b/i/u/em/strong等任意标签,无需修改代码,同时支持标签嵌套场景,自带标签不匹配容错。
内容的提问来源于stack exchange,提问作者MyDaftQuestions
相关产品推荐
相关产品推荐

