4

你将如何用一个<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();
}

所有表都确实被删除了,所以我确定我正在访问正确的节点。

4

2 回答 2

7

它可能有点难看,但您可以像这样编辑 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 告诉我这是一个只读属性。

编辑

我正在玩一些代码来解决这个问题,并看到它在被调用后oldElement.ParentNode变成了<div>节点。AppendChild()我找到的解决方案是HtmlNode在 if 块的开头创建另一个来保存父节点,然后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);
}
于 2012-07-18T14:02:09.570 回答
1

看看CsQuery,一个 jQuery 的 C# 端口。这很容易实现。首先加载文档:

CQ doc = CQ.CreateFromFile(..)  // or
CQ doc = CQ.CreateFromUrl(..)   // or
CQ doc = CQ.Create(string)

创建要包装的结构,这里有四种不同的方法可以做到这一点。

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();
于 2012-07-18T12:10:37.427 回答