/***** Code de MesExemples.com *******/
/**
* @(#)ListeNoeud.java
*
*
* @author
*sakoba(java.mesexemples.com) @version 1.00 2013/7/4
*/
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ListeNoeud {
public static void main(String[] args) throws Exception {
File file = new File("test.xml");
DocumentBuilder builder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(file);
// Parcourir le Noeud "Note"
NodeList nodes = doc.getElementsByTagName("note");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
// Accéder au sous-noeud "to"
NodeList title = element.getElementsByTagName("to");
Element line = (Element) title.item(0);
// Afficher son texte
System.out.println("Title: " + getCharacterDataFromElement(line));
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}
Code testé avec le fichier XML Suivant
Sakoba
Adams
Rappel
Ne m'oubliez pas ce week-end!