HTML敏捷包

jay*_*t55 11 html c# parsing winforms html-agility-pack

我正在尝试使用HTML Agility Pack从以下内容中获取描述文本:

<meta name="description" content="**this is the text i want to extract and store in a string**" />
Run Code Online (Sandbox Code Playgroud)

不久前有人在Stackoverflow上建议我使用HTMLAgilityPack.但我不知道如何使用它,我找到的文档(包括下载中包含的文档)都有无效的链接,因此无法查看文档.

有人可以帮我解决这个问题吗?

Mar*_*ell 18

用法非常相似XmlDocument; 您可以使用MSDN XmlDocument进行广泛的概述; 您可能还想学习xpath语法(MSDN).

例:

HtmlDocument doc = new HtmlDocument();
doc.Load(path); // or .LoadHtml(html);
HtmlNode node = doc.DocumentNode.SelectSingleNode("//meta[@name='description']");
if (node != null) {
    string desc = node.GetAttributeValue("content", "");
    // TODO: write desc somewhere
}
Run Code Online (Sandbox Code Playgroud)

第二个参数GetAttributeValue是在找不到属性时返回的默认值.

  • "def"代表默认值.如果找不到该属性,则返回该值.在这里评论,因为这是搜索答案时的最佳结果. (3认同)