2010-11-03 11 views
6

Tutto quello che voglio fare èHtmlAgilityPack HasAttribute?

node.Attributes["class"].Value 

Ma se il nodo non ha l'attributo class, si blocca. Quindi, devo prima verificarne l'esistenza, giusto? Come lo faccio? Attributes non è un dict (è un elenco che contiene un comando interno ??) e non esiste un metodo HasAttribute (solo un HasAttributes che indica se ha qualsiasi attributo). Cosa faccio?

+2

Sei sicuro di controllare per 'node.Attributes [" classe "]' non restituisce nulla? –

+0

@Kirk: Giusto, sei ... pensavo che avesse gettato un'eccezione per qualche motivo. Buona chiamata – mpen

risposta

13

Prova questo:

String val; 
if(node.Attributes["class"] != null) 
{ 
    val = node.Attributes["class"].Value; 
} 

Oppure si potrebbe essere in grado di aggiungere questo

public static class HtmlAgilityExtender 
{ 
    public static String ValueOrDefault(this HtmlAttribute attr) 
    { 
     return (attr != null) ? attr.Value : String.Empty; 
    } 
} 

e quindi utilizzare

node.Attributes["class"].ValueOrDefault(); 

I havent provato che uno, ma dovrebbe funzionare.

+0

Non puoi dichiarare una variabile su un'istruzione 'if' a riga singola ... –

+0

hehe, grazie per essere sveglio, quindi non devo :-) –

+0

vorrei che implementassero qualcosa come val = node.Attributes ["class"]. Valore ??? ""; se non ti importa nulla dei null ovunque ... – Doggett

3

Si prega di provare questo:

String abc = String.Empty;  
     if (tag.Attributes.Contains(@"type")) 
     { 
      abc = tag.Attributes[@"type"].Value; 
     } 
0

Questo codice può essere utilizzato per ottenere tutto il testo tra due tag script.

String getURL(){ 
return @"some site address"; 
} 
List<string> Internalscripts() 
    { 
     HtmlAgilityPack.HtmlDocument doc = new HtmlWeb().Load((@"" + getURL())); 
     //Getting All the JavaScript in List 
     HtmlNodeCollection javascripts = doc.DocumentNode.SelectNodes("//script"); 
     List<string> scriptTags = new List<string>(); 
     foreach (HtmlNode script in javascripts) 
     { 
      if(!script.Attributes.Contains(@"src")) 
      { 
       scriptTags.Add(script.InnerHtml); 
      } 
     } 
     return scriptTags; 
    } 
Problemi correlati