Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't call getElementsByTagName on a node in Xerces or Neko?

hi all I'm trying to parse a DOM tree using Neko/Xerces in Java.

NodeList divs = this.doc.getElementsByTagName("DIV");
for(int i=0; i < divs.getLength(); i++) {
    NodeList images = divs.item(i).parentNode().getElementsByTagName("IMG");
    // operate on these
}

is what I'd ideally like to do. It seems I can only call getElementsByTagName on the document itself? Am I doing something wrong? Should I be able to call that on a Node element?

I can see from the docs it's not there: http://xerces.apache.org/xerces-j/apiDocs/org/w3c/dom/Node.html so maybe I need to do it another way?

thanks!

like image 501
James Avatar asked Jul 22 '10 23:07

James


1 Answers

A NodeList only returns Nodes and getElementsByTagName is only available on an Element node You therefore need to cast your Node to an element, here's an example below.

final NodeList images = ((Element)divs.item(i).getParentNode()).getElementsByTagName("IMG");

However be careful with this as it assumes that getParentNode() always returns an Element

This would be safer, but a lot more verbose

final Node n = divs.item(i).getParentNode();

if(n instanceof Element) {
    final Element e = (Element)n;
    e.getElementsByTagName("IMG");
}
like image 161
reevesy Avatar answered Nov 16 '22 02:11

reevesy