J. Doe J. Doe - 1 month ago 16
Java Question

get child nodes from parent (xml, java)

UPDATE
i was specifically targeting staff under some root node, not all "staff" elements in the whole document. i forgot to mention this important detail in the question. sorry guys.

i found this answer to my question:

getElementsByTagName

But with this data:



<one>
<two>
<three>
<company>

<staff id="1001">
<firstname>Golf</firstname>
<lastname>4</lastname>
<nickname>Schnecke</nickname>
<salary>1</salary>
</staff>
<staff id="2001">
<firstname>Audi</firstname>
<lastname>R8</lastname>
<nickname>Rennaudi</nickname>
<salary>1111111</salary>
</staff>
<staff id="2002">
<firstname>Skoda</firstname>
<lastname>xyz</lastname>
<nickname>xyz</nickname>
<salary>0.1</salary>
</staff>

</company>
</three>
</two>
</one>


and this code:

public static void parseXML2() {
File fXmlFile = new File("src\\main\\java\\staff.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = null;
try {
dBuilder = dbFactory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
Logger.getLogger(MyParser.class.getName()).log(Level.SEVERE, null, ex);
}
Document doc = null;
try {
doc = dBuilder.parse(fXmlFile);
} catch (SAXException ex) {
Logger.getLogger(MyParser.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MyParser.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("test");
System.out.println(doc.getElementsByTagName("company").item(0).getTextContent());

}


i dont get just one staff element, but all of them. how come?

i was expecting to get:

Golf
4
Schnecke
1


but instead i get this:

Golf
4
Schnecke
1


Audi
R8
Rennaudi
1111111


Skoda
xyz
xyz
0.1


looks like your post is mostly code, please add more details...yes the details are there.

Answer Source

You are almost there. If you want to get the text contents of the first staff node, then get the elements by that tag name:

System.out.println(doc.getElementsByTagName("staff").item(0).getTextContent());
                                         // ^^^^^^

Update

In case you want to get the first staff node under company, then you can find them with node type and node name checks. Here is a rudimentary loop to do this:

    Node companyNode = doc.getElementsByTagName("company").item(0);
    NodeList companyChildNodes = companyNode.getChildNodes();
    for (int i = 0; i < companyChildNodes.getLength(); i++) {
        Node node = companyChildNodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE && Objects.equals("staff", node.getNodeName())) {
            System.out.println(node.getTextContent());
            break;
        }
    }

You might want to refactor the for loop into a separate method.

You can use XPATH too. I think it's more concise:

    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("//company/staff[1]");
    NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    System.out.println(nl.item(0).getTextContent());

Explanation:

  • //company selects all the company tags, regardless where they are in the xml. It's the // that ignores the rest of the xml structure.
  • //company/staff selects all the staff tags that are under company tag.
  • [0] selects the first such item.