4

我正在使用 VS2010 并使用 HTMLAGilityPack1.4.6(来自 Net40 文件夹)。以下是我的 HTML

<html>

<body>


<div id="header">

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


</html>

我在 C# 中使用以下代码来访问“hd1”。请告诉我正确的方法。

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;
}

尝试了许多排列和组合...我得到空值。

请帮忙。

4

2 回答 2

4

您的问题是如何将数据加载到HtmlDocument. 为了从文件中加载数据,您应该使用Load(fileName)方法。但是您使用的是LoadHtml(htmlString)方法,该方法将其"E:\\file1.htm"视为文档内容。当 HtmlAgilityPack 尝试在字符串中查找h2标签时,它什么也找不到。E:\\file1.htm这是加载html文件的正确方法:

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";

或者,如果您正在使用节点集合,则在循环中处理它们:

// Collection of nodes
var patients = doc.DocumentNode.SelectNodes("//div[@class='patient'");
foreach (var patient in patients)
    patient.SetAttributeValue("style", "visibility: hidden");
于 2013-06-11T12:22:56.790 回答
1

你几乎在那里:

HtmlNode _hdPatient = htmlDoc.DocumentNode.SelectSingleNode("//h2[@id='hd1']");
_hdPatient.InnerHtml = "Patient SurName"
于 2013-06-11T12:06:55.597 回答