简体   繁体   中英

Add HTML tags to HTMLAgilityPack nodes

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM