HtmlAgilityPack create node from text
Let's assume I have this
<div>
<p>Bla bla bla specialword bla bla bla</p>
<p>Bla bla bla bla bla specialword</p>
</div>
I want to replace the word specialword
开发者_开发问答from my html with a node, for example <b>specialword</b>
. This is easy using string replacement, but I want to use the Html Agility Pack features.
Thanks.
HtmlNode has a method called ReplaceChild, should do the trick.
Updated after comment
HtmlAgilityPack has no reason to have that ability as it is pure string manipulation, if I'm reading you correctly, and .NET does that fine as-is :
HtmlNode div = doc.CreateElement("div");
div.InnerHtml = Regex.Replace("(.*?)specialword(.*?)","{1}<b>specialword</b>{2}");
Then find the node and do a replace from it's parent.
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;
using System.IO;
using HtmlAgilityPack;
namespace savepage
{
class Program
{
static void Main(string[] args)
{
//...
// using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
// {
string[] nametag = { "//img", "//div", "//p", "//li", "//pre", "//span", "//ul" };
Console.WriteLine("Enter address site:");
HtmlDocument doc = new HtmlWeb().Load(Console.ReadLine()); // get address site
// Console.WriteLine("Enter Tag:");
// all <td> tags in the document
Console.WriteLine("0=img ,1=div,2=p,3=li,4=pre,5=span,6=ul");
string name = nametag[int.Parse(Console.ReadLine()) ]; //get list array
Console.WriteLine(name);
// foreach (HtmlNode span in doc.DocumentNode.SelectNodes("//span"))
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\WriteLines2.txt"))
{
foreach (HtmlNode tag in doc.DocumentNode.SelectNodes(name))
{
// HtmlAttribute src = img.Attributes[@"src"];
// Console.WriteLine(img.InnerText);
Console.WriteLine(tag.InnerText);
file.WriteLine(tag.InnerText);
//doc.Save(@"c:\majid.txt");
}
}
Console.ReadKey();
// }
}
}
}
精彩评论