/***** Code de MesExemples.com *******/ /** * @(#)AfficherTextElement.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.Text; public class AfficherTextElement { public static void main (String[] args)throws Exception { File file = new File("test.xml"); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(file); findByID(doc, "to"); } public static void findByID(Document doc,String idName) { Element name = doc.getElementById(idName); if(name == null) { System.out.println("Aucun élément avec ID " + idName+ " n'existe"); } else { Text text = (Text)name.getFirstChild(); System.out.println("ID " + idName + " Nom " + text.getData()); } } } |
Code testé avec le fichier XML Suivant
<?xml version="1.0" encoding="windows-1252"?> <!-- Edited by MesEXemple.com --> <note> <to>Sakoba</to> <from>Adams</from> <heading>Rappel</heading> <body>Ne m'oubliez pas ce week-end!</body> </note> |
Cet article Java XML: Trouver un élément et afficher son texte* est apparu en premier sur .