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

c# html-agility-pack

我有一项任务要做。我需要检索特定idtaghrefid来自用户输入)。示例我有一个像这样的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>

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

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

一般承认的答案

如果我理解正确的话:

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

string tag = document2.GetElementbyId("yourid").Name;
string href = document2.GetElementbyId("yourid").GetAttributeValue("href", "");

热门答案

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

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


Related

许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow