我有一个HtmlDocument
可能或可能有适当的<head>
and <body>
部分或者可能只是一个 html 片段。不管怎样,我想通过一个函数来运行它,以确保它具有(更)正确的 html 结构。
我知道我可以通过查看是否有身体来检查它是否有身体
doc.DocumentNode.SelectSingleNode("//body");
一片空白。如果它没有主体,我将如何将 doc.DocumentNode 的内容包装在<body>
元素并将其分配回HtmlDocument
?
Edit:对于我想要做什么似乎有些困惑。用 jquery 术语来说:
$doc = $(document);
if( !$doc.has('body') ) {
$doc.wrapInner('body');
}
基本上,如果没有 body 元素,则在所有内容周围放置一个 body 元素。
你可以这样做:
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)