HtmlAgilityPack - 如何通过Id获取标签?

kno*_*wme 26 c# html-agility-pack

我有一项任务要做.我需要检索a taghref特定的id(id基于用户输入).示例我有html这样的

<manifest>

<item href="Text/Cover.xhtml" id="Cov" media-type="application/xhtml+xml" />
    <item href="Text/Back.xhtml" id="Back" media-type="application/xhtml+xml" />
  </manifest>
Run Code Online (Sandbox Code Playgroud)

我已经有了这个代码.请帮我.谢谢

HtmlAgilityPack.HtmlDocument document2 = new 

HtmlAgilityPack.HtmlDocument();
document2.Load(@"C:\try.html");
HtmlNode[] nodes = document2.DocumentNode.SelectNodes("//manifest").ToArray();

foreach (HtmlNode item in nodes)
{
    Console.WriteLine(item.InnerHtml);
}
Run Code Online (Sandbox Code Playgroud)

b00*_*il' 39

如果我理解正确的话:

HtmlAgilityPack.HtmlDocument document2 = new HtmlAgilityPack.HtmlDocument();
document2.Load(@"C:\try.html");

string tag = document2.GetElementbyId("yourid").Name;
string href = document2.GetElementbyId("yourid").GetAttributeValue("href", "");
Run Code Online (Sandbox Code Playgroud)

  • 注意"by"中的小写"b"......呃 (4认同)

har*_*r07 6

您可以使用以下XPath item通过其id属性值查找元素:

var id = "Back";
var query = $"//manifest/item[@id='{id}']";
HtmlNode node = document2.DocumentNode.SelectSingleNode(query);
string href = node.GetAttributeValue("href", "");
Run Code Online (Sandbox Code Playgroud)