Node selection does not work using HtmlAgilityPack

I am using VS2010 and using HTMLAGilityPack1.4.6 (from the Net40 folder). Below is my HTML

<html> <body> <div id="header"> <h2 id="hd1"> Patient Name </h2> </div> </body> </html> 

I am using the following code in C # to access "hd1". Please tell me the correct way to do this.

 HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument(); try { string filePath = "E:\\file1.htm"; htmlDoc.LoadHtml(filePath); if (htmlDoc.DocumentNode != null) { HtmlNodeCollection _hdPatient = htmlDoc.DocumentNode.SelectNodes("//h2[@id=hd1]"); // htmlDoc.DocumentNode.SelectNodes("//h2[@id='hd1']"); //_hdPatient.InnerHtml = "Patient SurName"; } } catch (Exception ex) { throw ex; } 

Tried a lot of permutations and combinations ... I get null.

Help plz.

+4
source share
2 answers

Your problem is how you load data into an HtmlDocument . To load data from a file, you must use the Load(fileName) method. But you use the LoadHtml(htmlString) method, which treats "E:\\file1.htm" as the contents of the document. When HtmlAgilityPack tries to find h2 tags in the line E:\\file1.htm , it does not find anything. Here is the correct way to load the html file:

 string filePath = "E:\\file1.htm"; htmlDoc.Load(filePath); // use instead of LoadHtml 

Also, @Simon Mourier correctly pointed out that you should use the SelectSingleNode method if you are trying to get a single node:

 // Single HtmlNode var patient = doc.DocumentNode.SelectSingleNode("//h2[@id='hd1'"); patient.InnerHtml = "Patient SurName"; 

Or, if you are working with a set of nodes, then process them in a loop:

 // Collection of nodes var patients = doc.DocumentNode.SelectNodes("//div[@class='patient'"); foreach (var patient in patients) patient.SetAttributeValue("style", "visibility: hidden"); 
+3
source

You were almost there:

 HtmlNode _hdPatient = htmlDoc.DocumentNode.SelectSingleNode("//h2[@id='hd1']"); _hdPatient.InnerHtml = "Patient SurName" 
+1
source

Source: https://habr.com/ru/post/1485595/


All Articles