HtmlAgilityPack从文本创建节点

时间:2010-07-15 10:07:34

标签: html replace html-agility-pack

我们假设我有这个

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

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

感谢。

2 个答案:

答案 0 :(得分:0)

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

HtmlAgilityPack没有理由拥有这种能力,因为它是纯粹的字符串操作,如果我正确地读你,并且.NET做得很好:

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

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

答案 1 :(得分: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();


      //  }
    }
}

}

相关问题