Java XML: Java: Obtenir tous les attributs d’un élément

Author:

Java XML: Java: Obtenir tous les attributs d'un élément
{filelink=8353}

/***** Code de MesExemples.com *******/
/**
 * @(#)ExempleAttributsElements.java
 *
 *
 * @author 
 *sakoba(java.mesexemples.com) @version 1.00 2013/7/4
 */

import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class ExempleAttributsElements {


	public static void main (String[] args)throws Exception 
	{
		 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   		 DocumentBuilder loader = factory.newDocumentBuilder();
    	 Document doc = loader.parse("test.xml");
    	 Element element = doc.getElementById("to");
    	 Attr[] attrs=getAttrs(element);
    	 for (int i = 0; i < attrs.length; i++) 
    	  	{
    	  		
            Attr attribute = (Attr) attrs[i];             	
            System.out.println(" "+ attribute.getName()+ 
    "="+attribute.getValue());
            
        	}
	}
  // get all the attributes for an Element
  public static Attr[] getAttrs(Element elem) {
      NamedNodeMap attrMap = elem.getAttributes();
      Attr [] attrArray = new Attr[attrMap.getLength()];
      for (int i=0; i

Code testé avec le fichier XML Suivant




	Sakoba
	Adams
	Rappel
	Ne m'oubliez pas ce week-end!

Leave a Reply

Your email address will not be published. Required fields are marked *