Parsing html with the HTML Agility Pack and Linq

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

I have the following HTML

(..)

 
   Test1 
   Data 
  

        
5条回答
  •  后悔当初
    2021-02-02 18:45

    As for your attempt, you have two issues with your code:

    1. ChildNodes is weird - it also returns whitespace text nodes, which don't have a class attributes (can't have attributes, of course).
    2. As James Walford commented, the spaces around the text are significant, you probably want to trim them.

    With these two corrections, the following works:

    var data =
          from tr in doc.DocumentNode.Descendants("tr")
          from td in tr.Descendants("td").Where(x => x.Attributes["class"].Value == "name")
         where td.InnerText.Trim() == "Test1"
        select tr;
    

提交回复
热议问题