Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
391 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 = "
<div class="overflow">
"
        + oldElement.OuterHtml +
        "
</div>
";
}

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.

Edit

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...