2016-05-10 7 views
10

Ho un compito da fare. Ho bisogno di recuperare il tag o href di uno specifico id (il id è basato sull'input dell'utente). esempio ho un html come questoHtmlAgilityPack - Come ottenere il tag da Id?

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

Ho già questo codice. Mi aiuti per favore. Grazie

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

risposta

12

Se ho capito bene, allora:

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

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

grazie. che funziona perfettamente – knowme

+0

Nessun problema, buona fortuna;) – nrkz

2

È possibile utilizzare il seguente XPath per trovare item elemento per il suo valore di attributo id:

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

Solo nel caso in cui siete non ha familiarità con il segno ('$'): [interprete stringa-interpolazione] (https://msdn.microsoft.com/en-us/library/dn961160.aspx?f=255&MSPPError=-2147217396) – har07

+0

come questo? ma come posso ottenere l'output di quel codice? lo sto facendo bene? perché mi dà errore in fase di esecuzione. scusa per la mia stupida domanda HtmlAgilityPack.HtmlDocument document2 = new HtmlAgilityPack.HtmlDocument(); document2.Load (@ "C: \ try.html"); var id = "Indietro"; var query = $ "// manifest/item [@id = '{id}']"; HtmlNode node = document2.DocumentNode.SelectSingleNode (query); MessageBox.Show (node.ToString()); – knowme

+0

@knowme aggiornato. – har07