c# - 使用 HTMLAgilityPack 将孤立文本放入标签中

标签 c# html html-agility-pack

如何将一段html的语法转换成这样

<div>
     some text
     <br/>
     goes in here
     <br/>
     with only br tags
     <br/>
     to separate it
     <br/>
</div>

为此

<div>
     <p>some text</p>
     <p>goes in here</p>
     <p>with only br tags</p>
     <p>to separate it</p>
</div>

在 C# 中使用 HTML Agility Pack?

最佳答案

一种可能的方式:

var html = @"<div>
     some text
     <br/>
     goes in here
     <br/>
     with only br tags
     <br/>
     to separate it
     <br/>
</div>";
var doc = new HtmlDocument();
doc.LoadHtml(html);
var div = doc.DocumentNode.SelectSingleNode("div");
//select all non-empty text nodes within <div>
var texts = div.SelectNodes("./text()[normalize-space()]");
foreach (var text in texts)
{
    //remove current text node
    text.Remove();
    //replace with : <p>current text node content</p>
    var p = doc.CreateElement("p");
    p.AppendChild(doc.CreateTextNode(text.InnerText));
    div.PrependChild(p);
}
//remove all <br/> tags within <div>
foreach (var selectNode in div.SelectNodes("./br"))
{
    selectNode.Remove();
}
//print result
Console.WriteLine(doc.DocumentNode.OuterHtml);

关于c# - 使用 HTMLAgilityPack 将孤立文本放入标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25548487/

相关文章:

c# - 如何从 Cudafy c# GPU 计算返回一个值?

c# - 通过 Javascript 从代码隐藏访问全局静态变量

html - 带有 css 选择器的表行扰流板

c# - 使用 HTML 敏捷包在节点选择器中搜索通配符

c# - HtmlAgilityPack - 追加节点

c# - Html Agility Pack - 按 ID 或类删除标签

c# - 如何通过 C# 在 Excel 中将公式值解析为文本

javascript - 从 map 中的点坐标查找具有名称的谷歌地图地点

javascript - 在 HTML5 中创建拖放编辑平台

javascript - 一直使用持续时间为 0 的 .animate 可以吗?有更好的选择吗?