How do I use HTML Agility Pack to edit an HTML snippet

后端 未结 2 691
Happy的楠姐
Happy的楠姐 2021-01-01 17:32

So I have an HTML snippet that I want to modify using C#.

This is a specialSearchWord that I want to link to &l
2条回答
  •  别那么骄傲
    2021-01-01 17:56

    Answers:

    1. There may be a way to do this but I don't know how. I suggest loading the entire document.
    2. Use a combination of XPath and regular expressions
    3. See the code below for a contrived example. You may have other constraints not mentioned but this code sample should get you started.

    Note that your Xpath expression may need to be more complex to find the div that you want.

    HtmlDocument doc = new HtmlDocument();
    
    doc.Load(yourHtmlFile);
    HtmlNode divNode = doc.DocumentNode.SelectSingleNode("//div[2]");
    string newDiv = Regex.Replace(divNode.InnerHtml, @"specialSearchWord", 
    "specialSearchWord");
    divNode.InnerHtml = newDiv;
    Console.WriteLine(doc.DocumentNode.OuterHtml);
    

提交回复
热议问题