使用HtmlAgilityPack包装元素吗? [英] Wrap in an element with HtmlAgilityPack?
问题描述
我有一个HtmlDocument
,它可能或可能有一个正确的<head>
和<body>
部分,或者可能只是一个html片段.无论哪种方式,我都希望通过一个函数来运行它,以确保它具有(更多)正确的html结构.
I have an HtmlDocument
that may or may have a proper <head>
and <body>
section or might just be an html fragment. Either way, I want to run it through a function that will ensure that it has (more) proper html structure.
我知道我可以通过查看是否有尸体来
I know that I can check if it has a body by seeing if
doc.DocumentNode.SelectSingleNode("//body");
为空.如果没有主体,我该如何将doc.DocumentNode的内容包装在<body>
元素中,并将其分配回HtmlDocument
?
is null. If it does not have a body, how would I wrap the contents of doc.DocumentNode in a <body>
element and assign it back to the HtmlDocument
?
编辑:对于我想做的事情似乎有些困惑.用jquery术语:
There seems to be some confusion about what I want to do. In jquery terms:
$doc = $(document);
if( !$doc.has('body') ) {
$doc.wrapInner('body');
}
基本上,如果没有body元素,则在所有内容周围放置一个body元素.
Basically, if there is no body element, put a body element around everything.
推荐答案
您可以执行以下操作:
HtmlDocument doc = new HtmlDocument();
doc.Load(MyTestHtm);
HtmlNode body = doc.DocumentNode.SelectSingleNode("//body");
if (body == null)
{
HtmlNode html = doc.DocumentNode.SelectSingleNode("//html");
// we presume html exists
body = CloneAsParentNode(html.ChildNodes, "body");
}
static HtmlNode CloneAsParentNode(HtmlNodeCollection nodes, string name)
{
List<HtmlNode> clones = new List<HtmlNode>(nodes);
HtmlNode parent = nodes[0].ParentNode;
// create a new parent with the given name
HtmlNode newParent = nodes[0].OwnerDocument.CreateElement(name);
// insert before the first node in the selection
parent.InsertBefore(newParent, nodes[0]);
// clone all sub nodes
foreach (HtmlNode node in clones)
{
HtmlNode clone = node.CloneNode(true);
newParent.AppendChild(clone);
}
// remove all sub nodes
foreach (HtmlNode node in clones)
{
parent.RemoveChild(node);
}
return newParent;
}
这篇关于使用HtmlAgilityPack包装元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!