2012-07-19 27 views
7

Estoy tratando de analizar CDATA tpyes en XML. El código funciona bien e imprimirá Enlaces: en la consola (unas 50 veces, porque así es la cantidad de enlaces que tengo) pero los enlaces no aparecerán ... es solo un espacio de consola en blanco. ¿Qué podía faltar ``Lectura de CDATA XML en Java

package Parse; 

import java.io.File; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import org.w3c.dom.CharacterData; 
import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 

public class XMLParse { 
    public static void main(String[] args) throws Exception { 
    File file = new File("c:test/returnfeed.xml"); 
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
    Document doc = builder.parse(file); 

    NodeList nodes = doc.getElementsByTagName("video"); 
    for (int i = 0; i < nodes.getLength(); i++) { 
     Element element = (Element) nodes.item(i); 
     NodeList title = element.getElementsByTagName("videoURL"); 
     Element line = (Element) title.item(0); 
     System.out.println("Links: " + getCharacterDataFromElement(line)); 
    } 
    } 
    public static String getCharacterDataFromElement(Element e) { 
    Node child = e.getFirstChild(); 
    if (child instanceof CharacterData) { 
     CharacterData cd = (CharacterData) child; 
     return cd.getData(); 
    } 
    return ""; 
    } 
} 

Resultado:?

Links: 

Links: 

Links: 

Links: 

Links: 

Links: 

Links: 

XML de ejemplo: (No el documento completo)

<?xml version="1.0" ?> 
<response xmlns:uma="http://websiteremoved.com/" version="1.0"> 

    <timestamp> 
     <![CDATA[ July 18, 2012 5:52:33 PM PDT 
      ]]> 
    </timestamp> 
    <resultsOffset> 
     <![CDATA[ 0 
      ]]> 
    </resultsOffset> 
    <status> 
     <![CDATA[ success 
     ]]> 
    </status> 
    <resultsLimit> 
     <![CDATA[ 207 
     ]]> 
    </resultsLimit> 
    <resultsCount> 
     <![CDATA[ 207 
     ]]> 
    </resultsCount> 
    <videoCollection> 
     <name> 
      <![CDATA[ Video API 
      ]]> 
     </name> 
     <count> 
      <![CDATA[ 207 
      ]]> 
     </count> 
     <description> 
      <![CDATA[ 
      ]]> 
     </description> 
     <videos> 
      <video> 
       <id> 
        <![CDATA[ 8177840 
        ]]> 
       </id> 
       <headline> 
        <![CDATA[ Test1 
        ]]> 
       </headline> 
       <shortHeadline> 
        <![CDATA[ Test2 
        ]]> 
       </shortHeadline> 
       <description> 
        <![CDATA[ Test3 

        ]]> 
       </description> 
       <shortDescription> 
        <![CDATA[ Test4 

        ]]> 
       </shortDescription> 
       <posterImage> 
        <![CDATA[ http://a.com.com/media/motion/2012/0718/los_120718_los_bucher_on_howard.jpg 

        ]]> 
       </posterImage> 
       <videoURL> 
        <![CDATA[ http://com/removed/2012/0718/los_120718_los_bucher_on_howard.mp4 

        ]]> 
       </videoURL> 
      </video> 
     </videos> 
    </videoCollection> 
</response> 
+0

¿podría proporcionar un ejemplo xml? o una parte de eso? – Sujay

+0

XML agregado. Estoy tratando de obtener la URL http en la etiqueta "videoURL". – Matt

+0

¿Estás seguro de tener solo un nodo hijo 'Node child = e.getFirstChild();' ? Obtenga todos los nodos secundarios e inspecciónelos en el depurador. –

Respuesta

12

En lugar de verificar el primer hijo, sería prudente si el nodo tiene otros hijos también. En su caso (y supongo que si hubiera depurado ese nodo, lo hubiera sabido), el nodo pasado al método getCharacterDataFromElement tenía varios hijos. Actualicé el código y éste podría darle los indicadores en la dirección correcta:

public static String getCharacterDataFromElement(Element e) { 

    NodeList list = e.getChildNodes(); 
    String data; 

    for(int index = 0; index < list.getLength(); index++){ 
     if(list.item(index) instanceof CharacterData){ 
      CharacterData child = (CharacterData) list.item(index); 
      data = child.getData(); 

      if(data != null && data.trim().length() > 0) 
       return child.getData(); 
     } 
    } 
    return ""; 
} 
+0

Esto funcionó. Gracias Sujay! – Matt

+0

contento de ayudar! por favor considere aceptar la respuesta si esto ayudó :) – Sujay

+0

usted es el mejor –