So I have this XML File:
And what I am trying to do is to gain access to the children from "planView" using this code:
File file = new File(fileName);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(fileName);
NodeList myList = document.getElementsByTagName("planView");
for (int i = 0; i < myList.getLength(); i++) {
Node nNode = myList.item(i);
Element eElement = (Element) nNode;
System.out.println("idx is " + i +" and node is " + nNode + " and elem is " + eElement);
}
And this is the output (from System.out.println):
idx is 0 and node is [planView: null] and elem is [planView: null]
Why is the node from the planview null?
Child nodes of planView
needs to be accessed via method getChildNodes()
:
NodeList planViews = document.getElementsByTagName("planView");
for (int i = 0; i < planViews.getLength(); i++) {
Node planView = planViews.item(i);
for (int j = 0; j < planView.getChildNodes().getLength(); j++) {
Node n = planView.getChildNodes().item(j);
if (n instanceof Element) {
Element e = (Element) n;
System.out.println("s: " + e.getAttribute("s"));
}
}
}
It prints something like:
s: 0.000e+00
s: 1.000e+01