Hi,
I am trying to learn how to read XML files in Java. I find it really difficult to grasp the structure of the DOM and how to operate on Nodes. I have read tons of tutorials but most provide just the code with litte or no explanation what is happening.
Here is the XML file I am trying to read:
And here is the code that supposed to output the firstnames of staff:Code:<?xml version="1.0"?>
<company>
<staff>
<firstname>test</firstname>
<lastname>test2</lastname>
<nickname>test3</nickname>
<salary>test4</salary>
</staff>
<staff>
<firstname>test5</firstname>
<lastname>test6</lastname>
<nickname>test7</nickname>
<salary>test8</salary>
</staff>
</company>
However, the output is just "null null".Code:import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.File;
public class Test {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("/Users/Eleeist/Desktop/test.xml"));
Element companyElement = document.getDocumentElement();
NodeList elements = companyElement.getElementsByTagName("firstname");
System.out.println(elements.item(0).getNodeValue() + " " + elements.item(1).getNodeValue());
}
}
Could somebody please explain to me what is happening and what should I do to make it work? :)
Thanks.

