作成したxmlファイルからいくつかの属性を出力する必要があります。XMLファイルを読み込んでコンソールに出力する
これまでのところ、私はMKyoungに触発され、彼にいくつかの変更を加えました。しかし、私はxml属性を取得できません。私はその名前とスコアに名前を印刷したい。
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();
}
}
そしてhighscore.xmlという名前の私のxmlファイルには、この含まれています:
<score name="Rasmus" score="10000"/>
それを取得するための私のコードがある
<?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>
あなたはノードの次のレベルを反復処理する必要があります。 [私の答え](https://stackoverflow.com/a/47248264/5832518)を確認してください – Raju