Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get child Node of another Node, given node name

Tags:

java

dom

xml

I have an XML like this:

<documentslist>   <document>     <docnumber>1</docnumber>     <docname>Declaration of Human Rights</docname>     <aoo>lib</aoo>   </document>   <document>     <docnumber>2</docnumber>     <docname>Fair trade</docname>     <aoo>lib</aoo>   </document>   <document>     <docnumber>3</docnumber>     <docname>The wars for water</docname>     <aoo>lib</aoo>   </document>   <!-- etc. --> </documentslist> 

I have this code:

//XML parsing Document docsDoc = null; try {     DocumentBuilder db = dbf.newDocumentBuilder();     docsDoc = db.parse(new InputSource(new StringReader(xmlWithDocs))); } catch(ParserConfigurationException e) {e.printStackTrace();} catch(SAXException e) {e.printStackTrace();} catch(IOException e) {e.printStackTrace();} //retrieve document elements NodeList docs = docsDoc.getElementsByTagName("document");  if (docs.getLength() > 0){     //print a row for each document     for (int i=0; i<docs.getLength(); i++){         //get current document         Node doc = docs.item(i);         //print a cell for some document children         for (int j=0; j<columns.length; j++){             Node cell;             //print docname             cell = doc.getElementsByTagName("docname").item(0); //doesn't work             System.out.print(cell.getTextContent() + "\t");             //print aoo             cell = doc.getElementsByTagName("aoo").item(0); //doesn't work             System.out.print(cell.getTextContent() + "\t");         }         System.out.println();     } } 

But, as you know Node hasn't got getElementsByTagName method... Only Document has it. But I can't do docsDoc.getElementsByTagName("aoo"), because it will return me all <aoo> nodes, not only the one existing in the <document> node I'm inspecting.

How could I do it? Thanks!

like image 455
bluish Avatar asked Apr 06 '11 14:04

bluish


People also ask

Can NodeList have child nodes?

Child nodes include elements, text and comments. Note: The NodeList being live means that its content is changed each time new children are added or removed. The items in the collection of nodes are objects, not strings. To get data from node objects, use their properties.

What does childNodes return?

childNodes returns nodes: Element nodes, text nodes, and comment nodes. Whitespace between elements are also text nodes.

Which of the following properties returns a collection of a nodes child nodes as a NodeList?

The HTML DOM childNodes property returns a collection of node's child nodes in the form of a NodeList object.


1 Answers

If the Node is not just any node, but actually an Element (it could also be e.g. an attribute or a text node), you can cast it to Element and use getElementsByTagName.

like image 103
jarnbjo Avatar answered Oct 05 '22 23:10

jarnbjo