Parsing html with the HTML Agility Pack and Linq

前端 未结 5 1634
别跟我提以往
别跟我提以往 2021-02-02 18:21

I have the following HTML

(..)

 
   Test1 
   Data 
  

        
5条回答
  •  耶瑟儿~
    2021-02-02 19:00

    Here is the XPATH way - hmmm... everyone seems to have forgotten about the power XPATH and concentrate exclusively on C# XLinq, these days :-)

    This function gets all data values associated with a name:

    public static IEnumerable GetData(HtmlDocument document, string name)
    {
        return from HtmlNode node in
            document.DocumentNode.SelectNodes("//td[@class='name' and contains(text(), '" + name + "')]/following-sibling::td")
            select node.InnerText.Trim();
    }
    

    For example, this code will dump all 'Test2' data:

        HtmlDocument doc = new HtmlDocument();
        doc.Load(yourHtml);
    
        foreach (string data in GetData(doc, "Test2"))
        {
            Console.WriteLine(data);
        }
    

提交回复
热议问题