2010-11-03 18 views
6

Todo lo que quiero hacer esHtmlAgilityPack HasAttribute?

node.Attributes["class"].Value 

Pero si el nodo no tiene el atributo class, se bloquea. Entonces, primero tengo que verificar su existencia, ¿verdad? ¿Cómo puedo hacer eso? Attributes no es un dict (es una lista que contiene un dict interno?), Y no hay un método HasAttribute (solo un HasAttributes que indica si tiene algún atributo). ¿Qué debo hacer?

+2

¿Seguro comprobación de 'node.Attributes [ "clase"]' no vuelve nula? –

+0

@Kirk: está bien ... pensé que arrojó una excepción por alguna razón. Buena llamada. – mpen

Respuesta

13

Prueba esto:

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

O usted podría ser capaz de añadir este

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

y luego usar

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

que no he probado que uno, pero debería funcionar.

+0

No se puede declarar una variable en una declaración 'if' de una sola línea ... –

+0

jeje, gracias por estar despierto, así que no tengo que :-) –

+0

desearía que implementaran algo como val = node.Attributes ["clase"]. ¿Valor? ""; si simplemente no le importan los nulos en cualquier lugar ... – Doggett

3

Por favor, intente esto:

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

Este código se puede utilizar para obtener todo el texto entre dos etiquetas de 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; 
    } 
Cuestiones relacionadas