나는 적절한 <head>
및 <body>
섹션이 있거나 있을지도 모르는 HtmlDocument
를 HtmlDocument
거나 HTML 조각 일 수도 있습니다. 어느 쪽이든, 나는 (더) 적절한 html 구조를 갖도록하는 함수를 통해 그것을 실행하고 싶다.
나는 그것이 신체가 있는지를 확인할 수 있는지를 안다.
doc.DocumentNode.SelectSingleNode("//body");
null 본문이 없으면 doc.DocumentNode의 내용을 <body>
요소에 래핑하고 HtmlDocument
다시 할당하려면 어떻게해야합니까?
편집 : 내가하고 싶은 것에 대해 약간의 혼란이있는 것 같습니다. 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;
}