Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: org.apache.xerces.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element

Tags:

java

dom

xml

XML:

<nativeInformation>
       <detail id="natural:fieldFormat">A</detail>
</nativeInformation>

I am trying to get the "id" value. but keep getting this error: org.apache.xerces.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element

My code:

  for (int i = 0; i < nodeList.getLength(); i++) {
      String s;
      Node n = nodeList.item(i);         
      Attr attrName = ((Element) n).getAttributeNode("id");          
      if (attrName.getValue()!=null) {
           s = attrName.getValue();
           System.out.println(s);              
      } 
     } 

If I write : System.out.println("parent node is "+n.getParentNode()); inside the for loop that will give me, [detail: null]

Any help will be really appreciated.

like image 595
ron Avatar asked Jan 16 '14 19:01

ron


2 Answers

Before casting Node to Element you need to check that the Node is an Element. This is the way to convert Node into Element:

NodeList nodes = root.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
    if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) nodes.item(i);
    }
}
like image 74
Naren Avatar answered Nov 08 '22 18:11

Naren


see this code:

Node n = nodeList.item(i);
final NamedNodeMap attrs = n.getAttributes();
if(attrs !=null){
  Node id = attrs.getNamedItem("id");
  if(id !=null){
    System.out.println("id: "+id.getNodeValue());     
  }
}
like image 34
amir azizkhani Avatar answered Nov 08 '22 17:11

amir azizkhani