<div class="overflow"></div>
ノードを使って、どのようにすべてのテーブルを囲むことになりますか?これは明らかにそれをしません:
if (oldElement.Name == "table")
{
HtmlDocument doc = new HtmlDocument();
HtmlNode newElement = doc.CreateElement("div");
newElement.SetAttributeValue("class", "overflow");
newElement.AppendChild(oldElement);
oldElement.ParentNode.ReplaceChild(newElement, oldElement);
}
私はそのコードを試してもテーブルに何も起こりません。しかし、私が使用する場合:
if (oldElement.Name == "table")
{
oldElement.Remove();
}
すべてのテーブルが削除されているので、正しいノードにアクセスしているはずです。
ちょっと醜いかもしれませんが、oldElement.ParentNodeノードのInnerHtml属性を次のように編集することができます:
if (oldElement.Name == "table")
{
oldElement.ParentNode.InnerHtml = "\r\n<div class=\"overflow\">\r\n"
+ oldElement.OuterHtml +
"\r\n</div>\r\n";
}
また、oldElementのOuterHtml属性を編集できるようには見えません(これがParentNodeを最初に取得しなければならない理由です)。 HtmlAgilityPackはあなたがOuterHtmlを取得/設定できると言っていますが、VS2010はそれが読み取り専用のプロパティであると私に言っていました。
編集
私はこれを理解するためにいくつかのコードを使い、 AppendChild()
が呼び出された後、 oldElement.ParentNode
が<div>
ノードになるのを見ていoldElement.ParentNode
。私が見つけた解決策は、ifブロックの先頭に別のHtmlNode
を作成して親を保持し、最後にそのノードのReplaceChild()
を呼び出すことReplaceChild()
。
if (oldElement.Name == "table")
{
HtmlNode theParent = oldElement.ParentNode;
HtmlDocument doc = new HtmlDocument();
HtmlNode newElement = doc.CreateElement("div");
newElement.SetAttributeValue("class", "overflow");
newElement.AppendChild(oldElement);
theParent.ReplaceChild(newElement, oldElement);
}
jQueryのC#ポートであるCsQueryを見てください 。これは容易に達成することができます。まずドキュメントをロードします:
CQ doc = CQ.CreateFromFile(..) // or
CQ doc = CQ.CreateFromUrl(..) // or
CQ doc = CQ.Create(string)
あなたがそれを行うことができる4つの異なる方法は、ここでラップする構造を作成します。
var wrap = CQ.CreateFragment("<div class='overflow'></div>"); // or
// you can pass HTML as a selector as in jQuery. The property indexer for a CQ
// object is the default method, same as $(..)
var wrap = doc["<div class='overflow'></div>"]; // or
var wrap = doc["<div />"].AddClass("overflow"); // or
// creates an element directly, sames as browser DOM methods
var wrap = doc.Document.CreateElement("div");
wrap.ClassName="overflow";
次の構造体ですべてのテーブルをラップします。
doc["table"].Wrap(wrap); // or use longhand for the Select method
doc.Select("table").Wrap(wrap);
完全なドキュメントを文字列にレンダリングする:
string html = doc.Render();