Add HTML tags to HTMLAgilityPack nodes

c# html-agility-pack visual-studio

Question

I need to parse through a CMS generated HTML page and add list item tags around any HTMLAgiligyPack nodes with a child node that have a name attribute of "Example".

C# code

HtmlDocument doc = new HtmlDocument();
doc.Load("test.htm");
foreach (HtmlNode docObjects in doc.DocumentNode.SelectNodes("//object[@type='text/sitemap']"))
{
  HtmlNodeCollection paramNodes = docObjects.ChildNodes;
  foreach (HtmlNode paramNode in paramNodes)
  {
    string paramName = paramNode.GetAttributeValue("name", null);
    string paramValue = paramNode.GetAttributeValue("value", null);
    HtmlNode findItem = paramNode.NextSibling;
    if (paramName == "Example")
    {
     //Add listitem (<li>) tags to the paramName node 
    }
  }
}

test.htm

<OBJECT type="text/sitemap">
    <param name="Example" value="Help.chm::\toc.hhc">
</OBJECT>
<OBJECT type="text/sitemap">
    <param name="Example" value="Help2.chm::\toc.hhc">
</OBJECT>
<OBJECT type="text/sitemap">
    <param name="Example" value="Help3.chm.chm::\toc.hhc">
</OBJECT>

needs to be

<li><OBJECT type="text/sitemap">
    <param name="Example" value="Help.chm::\testing.htm">
</OBJECT></li>
<li><OBJECT type="text/sitemap">
    <param name="Example" value="Help2.chm::\testing.htm">
</OBJECT></li>
<li><OBJECT type="text/sitemap">
    <param name="Example" value="Help3.chm::\testing.htm">
</OBJECT></li>

Any assistance you can provide would be greatly appreciated. This is part of a bigger project I'm working on and will likely be requesting help with in the future. Need a crash course back into C# - thanks you all ahead of time.

Accepted Answer

Here is one way (code goes within your if clause):

var objectNode = paramNode.ParentNode;
var li = doc.CreateElement("li");
objectNode.Remove();
li.AppendChild(objectNode);

doc.DocumentNode.AppendChild(li);



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why