我的 HTML 格式不正确,标签重叠:
<p>word1<b>word2</p>
<p>word3</b>word4</p>
重叠也可以嵌套。
如何使用 HTML Agility Pack (HAP) 将其转换为格式良好的 HTML?
我正在寻找这个输出:
<p>word1<b>word2</b></p>
<p><b>word3</b>word4</p>
I tried HtmlNode.ElementsFlags["b"] = HtmlElementFlag.Closed | HtmlElementFlag.CanOverlap
,但它没有按预期工作。
它实际上按预期工作,但可能不按预期工作you预期的。不管怎样,这里有一段示例代码(控制台应用程序),它演示了如何使用该库实现一些 HTML 修复。
图书馆有一个ParseErrors
您可以使用该集合来确定标记解析期间检测到的错误。
这里实际上有两种类型的问题:
1) 未封闭的元素。默认情况下,库已修复此问题,但 P 元素上有一个选项可以防止这种情况发生。
2) 未打开的元素。这个比较复杂,因为这取决于你想如何修复它,你想在哪里打开标签?在下面的示例中,我使用最近的前一个文本同级节点来打开该元素。
static void Main(string[] args)
{
// clear the flags on P so unclosed elements in P will be auto closed.
HtmlNode.ElementsFlags.Remove("p");
// load the document
HtmlDocument doc = new HtmlDocument();
doc.Load("yourTestFile.htm");
// build a list of nodes ordered by stream position
NodePositions pos = new NodePositions(doc);
// browse all tags detected as not opened
foreach (HtmlParseError error in doc.ParseErrors.Where(e => e.Code == HtmlParseErrorCode.TagNotOpened))
{
// find the text node just before this error
HtmlTextNode last = pos.Nodes.OfType<HtmlTextNode>().LastOrDefault(n => n.StreamPosition < error.StreamPosition);
if (last != null)
{
// fix the text; reintroduce the broken tag
last.Text = error.SourceText.Replace("/", "") + last.Text + error.SourceText;
}
}
doc.Save(Console.Out);
}
public class NodePositions
{
public NodePositions(HtmlDocument doc)
{
AddNode(doc.DocumentNode);
Nodes.Sort(new NodePositionComparer());
}
private void AddNode(HtmlNode node)
{
Nodes.Add(node);
foreach (HtmlNode child in node.ChildNodes)
{
AddNode(child);
}
}
private class NodePositionComparer : IComparer<HtmlNode>
{
public int Compare(HtmlNode x, HtmlNode y)
{
return x.StreamPosition.CompareTo(y.StreamPosition);
}
}
public List<HtmlNode> Nodes = new List<HtmlNode>();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)