Answer the question
In order to leave comments, you need to log in
How to get all child elements of an XML file using DOM in Java?
Good day to all! Faced a problem, there is an xml document
<?xml version="1.0" encoding="utf-8"?>
<schools>
<school id = "1">
<class>
<element_1>pupil_1</element_1>
<element_2>pupil_2</element_2>
<element_3>pupil_3</element_3>
</class>
<super_class>
<element_1>super_pupil_1</element_1>
<element_2>super_pupil_2</element_2>
<element_3>super_pupil_3</element_3>
</super_class>
</school>
<school id = "2">
<class>
<element_1>pupil_1</element_1>
<element_2>pupil_2</element_2>
<element_3>pupil_3</element_3>
</class>
<super_class>
<element_1>super_pupil_1</element_1>
<element_2>super_pupil_2</element_2>
<element_3>super_pupil_3</element_3>
</super_class>
</school>
<school id = "3">
<class>
<element_1>pupil_1</element_1>
<element_2>pupil_2</element_2>
<element_3>pupil_3</element_3>
</class>
<super_class>
<element_1>super_pupil_1</element_1>
<element_2>super_pupil_2</element_2>
<element_3>super_pupil_3</element_3>
</super_class>
</school>
</schools>
File fXmlFile = new File("demo.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :"
+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("school");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if (eElement.getAttribute("id").equals(findElement)) {
System.out.println("\nCurrent Element :"
+ nNode.getNodeName());
System.out.println("Staff id : "
+ eElement.getAttribute("id"));
System.out.println("Class element : "
+ eElement.getElementsByTagName("class").item(0).getTextContent().trim());
System.out.println("Super Class element : "
+ eElement.getElementsByTagName("super_class").item(0).getTextContent().trim());
}
}
Answer the question
In order to leave comments, you need to log in
I found the solution myself, what you need can be achieved using the following
Node el = eElement.getFirstChild();
do {
System.out.println(el.getTextContent());
el = el.getNextSibling();
} while (el != null);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question