java xml cast Node to Element
Sé que esto se me pidió muchas veces, pero aún no puedo hacerlo funcionar. Convierto una cadena XML a un objeto de documento y luego lo analizo. Aquí está el código:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
Document document = builder.parse( new InputSource( new StringReader( result ) ) );
Node head = document.getFirstChild();
if(head != null)
{
NodeList airportList = head.getChildNodes();
for(int i=0; i<airportList.getLength(); i++) {
Node n = airportList.item(i);
Element airportElem = (Element)n;
}
}
catch (Exception e) {
e.printStackTrace();
}
Cuando lanzo el objeto Nodo n al elemento, obtengo una excepción java.lang.ClassCastException: org.apache.harmony.xml.dom.TextImpl no se puede convertir en org.w3c.dom.Element. Cuando verifico el tipo de nodo del objeto Nodo, dice Node.TEXT_NODE. Creo que debería ser Node.ELEMENT_NODE. Estoy en lo cierto?
Entonces, ¿cómo convierto Nodo a Elemento, entonces puedo hacer algo como element.getAttribute ("attrName")?
Aquí está mi XML:
<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfCity xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<City>
<strName>Abu Dhabi</strName>
<strCode>AUH</strCode>
</City>
<City>
<strName>Amsterdam</strName>
<strCode>AMS</strCode>
</City>
<City>
<strName>Antalya</strName>
<strCode>AYT</strCode>
</City>
<City>
<strName>Bangkok</strName>
<strCode>BKK</strCode>
</City>
</ArrayOfCity>
¡Gracias por adelantado!