HtmlAgilityPack - How to get the tag by Id?

廉价感情. 提交于 2019-12-19 05:01:40

问题


I have a task to do. I need to retrieve the a tag or href of a specific id (the id is based from the user input). Example I have a html like this

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

I already have this code. Please, help me. Thank you

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

回答1:


If I understand correctly then:

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

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



回答2:


You can use the following XPath to find item element by its id attribute value :

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


来源:https://stackoverflow.com/questions/37130244/htmlagilitypack-how-to-get-the-tag-by-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!