[java] Get child Node of another Node, given node name

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!

This question is related to java xml dom

The answer is


Check if the Node is a Dom Element, cast, and call getElementsByTagName()

Node doc = docs.item(i);
if(doc instanceof Element) {
    Element docElement = (Element)doc;
    ...
    cell = doc.getElementsByTagName("aoo").item(0);
}

//xn=list of parent nodes......                
foreach (XmlNode xn in xnList)
{                                           
    foreach (XmlNode child in xn.ChildNodes) 
    {
        if (child.Name.Equals("name")) 
        {
            name = child.InnerText; 
        }
        if (child.Name.Equals("age"))
        {
            age = child.InnerText; 
        }
    }
}

You should read it recursively, some time ago I had the same question and solve with this code:

public void proccessMenuNodeList(NodeList nl, JMenuBar menubar) {
    for (int i = 0; i < nl.getLength(); i++) {
        proccessMenuNode(nl.item(i), menubar);
    }
}

public void proccessMenuNode(Node n, Container parent) {
    if(!n.getNodeName().equals("menu"))
        return;
    Element element = (Element) n;
    String type = element.getAttribute("type");
    String name = element.getAttribute("name");
    if (type.equals("menu")) {
        NodeList nl = element.getChildNodes();
        JMenu menu = new JMenu(name);

        for (int i = 0; i < nl.getLength(); i++)
            proccessMenuNode(nl.item(i), menu);

        parent.add(menu);
    } else if (type.equals("item")) {
        JMenuItem item = new JMenuItem(name);
        parent.add(item);
    }
}

Probably you can adapt it for your case.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to xml

strange error in my Animation Drawable How do I POST XML data to a webservice with Postman? PHP XML Extension: Not installed How to add a Hint in spinner in XML Generating Request/Response XML from a WSDL Manifest Merger failed with multiple errors in Android Studio How to set menu to Toolbar in Android How to add colored border on cardview? Android: ScrollView vs NestedScrollView WARNING: Exception encountered during context initialization - cancelling refresh attempt

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component