私は適切な<head>
と<body>
セクションを持っているかもしれないHtmlDocument
を持っているか、ちょうどhtmlフラグメントかもしれません。いずれにしても、適切なhtml構造を持っていることを保証する関数を実行したい。
私はそれが体を持っているかどうかを確認することができることを知っている
doc.DocumentNode.SelectSingleNode("//body");
無効である。本文がない場合は、 <body>
要素にdoc.DocumentNodeの内容をラップし、HtmlDocumentに割り当てる方法は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;
}