I need to printout some attributes from an xml file i've created.
So far i am inspired by MKyoung and have made some changes in his. But i cant get the xml attributes. I want to print out the name in the "" and the score.
<score name="Rasmus" score="10000"/>
My code for getting it is:
public void readXMLFile() {
try {
File fXmlFile = new File("highscore.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root element : " + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Highscore");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element : " + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Name : " + eElement.getAttribute("score"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
And my xml file named highscore.xml contains this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Highscore>
<score name="Rasmus" score="10000"/>
<score name="Søren" score="6000"/>
<score name="Niclas" score="5000"/>
</Highscore>