以下代码将TagBuilder
转换为String
。
有什么反面吗?如何将String
反向转换为TagBuilder
?
寻找解决方案。
Convert IHtmlContent/TagBuilder to string in C#
public static string GetString(IHtmlContent content)
{
using (var writer = new System.IO.StringWriter())
{
content.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
最佳答案
作为一种选择,您可以使用 HtmlAgilityPack
这样的html解析器并获取html节点,然后使用节点的名称,属性和内部html创建 TagBuilder
:
public TagBuilder GetTagBuilder(string html)
{
var node = HtmlAgilityPack.HtmlNode.CreateNode(html);
var tagBuilder = new TagBuilder(node.Name);
tagBuilder.MergeAttributes(node.Attributes.ToDictionary(x => x.Name, x => x.Value));
tagBuilder.InnerHtml = node.InnerHtml;
return tagBuilder;
}
例如:
var html = @"<div id=""div1"" class=""class1"">Something</div>";
var tagBuilder = GetTagBuilder(html);
var str = tagBuilder.ToString();
那么
str
的值将是:<div class="class1" id="div1">Something</div>
关于c# - 净核心: Convert String to TagBuilder,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56911086/