title: java xml cast Node to Element
body: <p>I know this was asked many times but I still cannot get it to work. I convert xml string to Document object and then parse it. Here is the code:</p>
  
  <pre><code>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&lt;airportList.getLength(); i++) {
      Node n = airportList.item(i);                        
      Element airportElem = (Element)n;
    }
  }
  catch (Exception e) {
    e.printStackTrace();
  } 
  </code></pre>
  
  <p>When I cast the Node object n to Element I get an exception java.lang.ClassCastException: org.apache.harmony.xml.dom.TextImpl cannot be cast to org.w3c.dom.Element. When I check the node type of the Node object it says Node.TEXT_NODE. I believe it should be Node.ELEMENT_NODE. Am I right? </p>
  
  <p>So how do I convert Node to Element, so I can do something like element.getAttribute("attrName"). </p>
  
  <p>Here is my XML:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; 
  &lt;ArrayOfCity xmlns:xsd="http://www.w3.org/2001/XMLSchema"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" &gt;
  &lt;City&gt;
    &lt;strName&gt;Abu Dhabi&lt;/strName&gt; 
    &lt;strCode&gt;AUH&lt;/strCode&gt; 
  &lt;/City&gt;
  &lt;City&gt;
    &lt;strName&gt;Amsterdam&lt;/strName&gt; 
    &lt;strCode&gt;AMS&lt;/strCode&gt; 
  &lt;/City&gt;
  &lt;City&gt;
    &lt;strName&gt;Antalya&lt;/strName&gt; 
    &lt;strCode&gt;AYT&lt;/strCode&gt; 
  &lt;/City&gt;
  &lt;City&gt;
    &lt;strName&gt;Bangkok&lt;/strName&gt; 
    &lt;strCode&gt;BKK&lt;/strCode&gt; 
  &lt;/City&gt;
  &lt;/ArrayOfCity&gt;
  </code></pre>
  
  <p>Thanks in advance!</p>