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!
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.
childNodes returns nodes: Element nodes, text nodes, and comment nodes. Whitespace between elements are also text nodes.
The HTML DOM childNodes property returns a collection of node's child nodes in the form of a NodeList object.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With