围绕现有节点与敏捷性包的另一个节点 [英] Surround existing node with another node with Agility Pack

查看:251
本文介绍了围绕现有节点与敏捷性包的另一个节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您会如何去所有的表,围绕着一个< D​​IV CLASS =溢出>< / DIV> 节点?这显然​​不做到这一点:

How would you go about surrounding all tables with a <div class="overflow"></div> node? This apparently does not do it:

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);
}



什么也没有发生的表,当我尝试代码。但是,如果我使用:

Nothing happens to the tables when I try that code. But if i use:

if (oldElement.Name == "table")
{
    oldElement.Remove();
}



所有的表确实去除,所以我敢肯定我是访问正确的节点。

All tables are indeed removed, so I'm sure that i'm accessing the correct nodes.

推荐答案

这可能是有点难看,但你可以只编辑oldElement.ParentNode的innerHTML属性像这样的节点:

It might be a little bit ugly, but you could just edit the InnerHtml attribute of the oldElement.ParentNode node like so:

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告诉我这是一个只读属性。

It also doesn't seem like you could edit the OuterHtml attribute of oldElement (which is why you have to get the ParentNode first). The HtmlAgilityPack says you can get/set OuterHtml, but VS2010 was telling me it's a read-only property.

修改

我在玩弄一些代码摸不着头脑,看到 oldElement.ParentNode 变成了< DIV> 节点的appendChild()被调用。我找到了解决的办法是让另一个 HtmlNode 在IF块开始举办父,然后调用的replaceChild()末该节点上:

I was playing around with some code to figure this out and saw that oldElement.ParentNode becomes the <div> node after AppendChild() is called. The solution I found is to make another HtmlNode at the start of the if block to hold the parent, and then calling ReplaceChild() on that node at the end:

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);
}

这篇关于围绕现有节点与敏捷性包的另一个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆