如何将一段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/