Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

c# - Surround existing node with another node with Agility Pack

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...