Acceder al contenido y a los atributos de un Element

2046 vistas

Para acceder al contenido y a los atributos de un Element podemos usar los métodos getTextContent y getAttributesByTagName.

Veamos un ejemplo en el que se extrae de un XHTML los enlaces y sus propiedades:



java
  1. public static List<Element> getLinks(String xhtmlUrl) throws Exception{
  2.   List<Element> enlaces = new ArrayList<Element>();
  3.   InputStream stream = null;
  4.   try{
  5.     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  6.     factory.setValidating(true);
  7.     DocumentBuilder constructor = factory.newDocumentBuilder();
  8.     URL url = new URL(xhtmlUrl);
  9.     stream = url.openStream();
  10.     Document document = constructor.parse(stream);
  11.     Element raiz = document.getDocumentElement();
  12.     String tag = "a";
  13.     NodeList lista = raiz.getElementsByTagName(tag);
  14.     for(int i=0; i<liste.getLength(); i++){
  15.       Element e = (Element)lista.item(i);
  16.       if(e.hasAttribute("href")) enlaces.add(e);
  17.     }
  18.   }catch(Exception e){
  19.     throw e;
  20.   }finally{
  21.     try{stream.close();
  22.   }catch(Exception e) {}
  23.  
  24.   return enlaces;
  25.   }
  26. }



Ejemplo de uso:



java
  1. String url = "http://www.w3.org/";
  2. List<Element> enlaces = getLinks(url);
  3. for(Element enlace : enlaces){
  4.   String href = enlace.getAttribute("href");
  5.   String texto = enlace.getTextContent();
  6.   texto = (texto!=null)?texto:href;
  7.   System.out.println("Enlace "+texto+" apunta a "+href);
  8. }



Para más información sobre u Element (o atributo) definido por un schema, podemos usar el método getSchemaTypeInfo().