选择节点不适用于HtmlAgilityPack [英] selecting Node does not work using HtmlAgilityPack
问题描述
我正在使用VS2010和HTMLAGilityPack1.4.6(来自Net40文件夹).以下是我的HTML
I am using VS2010 and using HTMLAGilityPack1.4.6 (from Net40-folder). Following is my HTML
<html>
<body>
<div id="header">
<h2 id="hd1">
Patient Name
</h2>
</div>
</body>
</html>
我正在C#中使用以下代码访问"hd1".请告诉我正确的方法.
I am using following code in C# to access "hd1". Please tell me correct way to do it.
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 many permutations and combinations... I get null.
plz帮助.
推荐答案
您的问题是如何将数据加载到 HtmlDocument
中.为了从文件中加载数据,您应该使用 Load(fileName)
方法.但是您正在使用 LoadHtml(htmlString)
方法,该方法将"E:\\ file1.htm"
视为文档内容.当HtmlAgilityPack尝试在 E:\\ file1.htm
字符串中找到 h2
标记时,它什么也找不到.这是加载html文件的正确方法:
Your problem is the way how you load data into HtmlDocument
. In order to load data from file you should use Load(fileName)
method. But you are using LoadHtml(htmlString)
method, which treats "E:\\file1.htm"
as document content. When HtmlAgilityPack tries to find h2
tags in E:\\file1.htm
string, it finds nothing. Here is the correct way to load html file:
string filePath = "E:\\file1.htm";
htmlDoc.Load(filePath); // use instead of LoadHtml
@Simon Mourier也正确指出,如果要获取单个节点,则应使用 SelectSingleNode
方法:
// Single HtmlNode
var patient = doc.DocumentNode.SelectSingleNode("//h2[@id='hd1'");
patient.InnerHtml = "Patient SurName";
或者,如果您正在处理节点集合,则循环处理它们:
Or if you are working with collection 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");
这篇关于选择节点不适用于HtmlAgilityPack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!