2010-07-15 49 views
1

节点假设我有这个HtmlAgilityPack创建文本

<div> 
    <p>Bla bla bla specialword bla bla bla</p> 
    <p>Bla bla bla bla bla specialword</p> 
</div> 

我想从我的HTML与节点替换单词specialword,例如<b>specialword</b>。这很容易使用字符串替换,但我想使用Html Agility Pack功能。

谢谢。

+0

我不认为HtmlAgilityPack具有该功能。你可能只需要做字符串替换。 – 2010-07-16 20:42:04

+0

我首先从HTML片段创建一个文档,然后搜索其文本中包含所需单词的文本节点,然后用新值替换该单词。 – Alex 2013-02-06 18:25:50

回答

0

HtmlNode有一个名为ReplaceChild的方法,应该这样做。
评论后更新

HtmlAgilityPack没有理由没有那个能力,因为它是纯粹的字符串操作,如果我读你正确,和.NET确实细原样:

HtmlNode div = doc.CreateElement("div"); 
div.InnerHtml = Regex.Replace("(.*?)specialword(.*?)","{1}<b>specialword</b>{2}"); 

然后找到该节点并从其父节点进行替换。

+0

ReplaceChild与什么? – morsanu 2011-09-20 10:54:17

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


     // } 
    } 
} 

}