/***** Code de MesExemples.com *******/
/**
* @(#)ExempleXMLAttribut.java
*
*
* @author
*sakoba(java.mesexemples.com) @version 1.00 2013/7/4
*/
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ExempleXMLAttribut {
public static void main (String[] args)throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder loader = factory.newDocumentBuilder();
Document doc = loader.parse("test.xml");
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);
afficherAttributsDe(line);
}
}
public static void afficherAttributsDe(Element element) {
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
System.err.println("## prefix=" + node.getPrefix() + " localname:" +
node.getLocalName()
+ " value=" + node.getNodeValue());
}
}
}
Code testé avec le fichier XML Suivant
Sakoba
Adams
Rappel
Ne m'oubliez pas ce week-end!