IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Android Discussion :

Parser fichier XML


Sujet :

Android

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Homme Profil pro
    Etudiant
    Inscrit en
    Décembre 2011
    Messages
    9
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiant
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Décembre 2011
    Messages : 9
    Par défaut Parser fichier XML
    Salut,

    je suis debutant en android mon application consiste a parser une fichier xml en ligne et afficher dans un liste view.

    Voila mon fichier xml :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    <maintag>
    <item>
    <name>nom utilisateur</name>
    <website>www.nomutilisateur.com</website>
    </item>
    <item>
    <name>autrenom</name>
    <website>www.autrnom.com</website>
    </item>
     
     
    </maintag>
    voila fichier main.xml
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
     
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/hotel9"
        android:orientation="horizontal" >
     
        <ImageView
            android:id="@+id/img"
            android:layout_width="65dp"
            android:layout_height="120dp"
            android:layout_weight="1"
            android:padding="10dip" />
     
        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="230dp"
            android:layout_height="128dp"
            android:orientation="vertical"
            android:paddingLeft="10dip" >
     
            <TextView
                android:id="@+id/name"
                android:layout_width="224dp"
                android:layout_height="57dp"
                android:textSize="16dip"
                android:textStyle="bold"
                />
     
            <TextView
                android:id="@+id/website"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
     
    </LinearLayout>
    classe XMLParsingExample.java et l suivant
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
     
    package com.androidpeople.xml.parsing;
     
    import java.net.URL;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.InputSource;
    import org.xml.sax.XMLReader;
    import android.app.Activity;
    import android.os.Bundle;
     
    import android.widget.TextView;
     
    public class XMLParsingExample extends Activity {
     
    	/** Create Object For SiteList Class */
    	SitesList sitesList = null;
     
    	/** Called when the activity is first created. */
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
    		TextView nameTextView = (TextView) findViewById(R.id.name);
    		TextView webTextView = (TextView) findViewById(R.id.website);
     
     
     
    		try {
     
    			/** Handling XML */
    			SAXParserFactory spf = SAXParserFactory.newInstance();
    			SAXParser sp = spf.newSAXParser();
    			XMLReader xr = sp.getXMLReader();
     
    			/** Send URL to parse XML Tags */
    			URL sourceUrl = new URL(
    					"http://testandroid.hebergratuit.com/aaaa.xml");
     
    			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
    			MyXMLHandler myXMLHandler = new MyXMLHandler();
    			xr.setContentHandler(myXMLHandler);
    			xr.parse(new InputSource(sourceUrl.openStream()));
     
    		} catch (Exception e) {
    			System.out.println("XML Pasing Excpetion = " + e);
    		}
     
    		/** Get result from MyXMLHandler SitlesList Object */
    		sitesList = MyXMLHandler.sitesList;
     
     
    		for (int i = 0; i < sitesList.getName().size(); i++) {
     
     
     
     
     
    			nameTextView.setText(sitesList.getName().get(i));
    			nameTextView.setText("Name = "+sitesList.getName().get(i));
     
    			webTextView.setText("Website = "+sitesList.getWebsite().get(i));
    }}
    Voila class siteliste.java :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
     
    package com.androidpeople.xml.parsing;
     
    import java.util.ArrayList;
     
    /** Contains getter and setter method for varialbles  */
    public class SitesList {
     
    	/** Variables */
    	private ArrayList<String> name = new ArrayList<String>();
    	private ArrayList<String> website = new ArrayList<String>();
    	private ArrayList<String> category = new ArrayList<String>();
     
     
    	/** In Setter method default it will return arraylist 
             *  change that to add  */
     
    	public ArrayList<String> getName() {
    		return name;
    	}
     
    	public void setName(String name) {
    		this.name.add(name);
    	}
     
    	public ArrayList<String> getWebsite() {
    		return website;
    	}
     
    	public void setWebsite(String website) {
    		this.website.add(website);
    	}
    class MyXMLHandler :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
     
    package com.androidpeople.xml.parsing;
     
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
     
    public class MyXMLHandler extends DefaultHandler {
     
    	Boolean currentElement = false;
    	String currentValue = null;
    	public static SitesList sitesList = null;
     
    	public static SitesList getSitesList() {
    		return sitesList;
    	}
     
    	public static void setSitesList(SitesList sitesList) {
    		MyXMLHandler.sitesList = sitesList;
    	}
     
     
     
    	@Override
    	public void startElement(String uri, String localName, String qName,
    			) throws SAXException {
     
    		currentElement = true;
     
    		if (localName.equals("maintag"))
    		{
     
     
     
     
     
     
    	@Override
    	public void endElement(String uri, String localName, String qName)
    			throws SAXException {
     
    		currentElement = false;
     
    		/** set value */ 
    		if (localName.equalsIgnoreCase("name"))
    			sitesList.setName(currentValue);
    		else if (localName.equalsIgnoreCase("website"))
    			sitesList.setWebsite(currentValue);
     
    	}
     
    	/** Called to get tag characters ( ex:- <name>AndroidPeople</name> 
             * -- to get AndroidPeople Character ) */
    	@Override
    	public void characters(char[] ch, int start, int length)
    			throws SAXException {
     
    		if (currentElement) {
    			currentValue = new String(ch, start, length);
    			currentElement = false;
    		}
     
    	}
     
    }
    je veux afficher tous les item de fichier xml, mais mon application n'affiche rien .

    Merciiiiiiii

  2. #2
    Expert confirmé

    Avatar de Feanorin
    Profil pro
    Inscrit en
    Avril 2004
    Messages
    4 589
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2004
    Messages : 4 589
    Par défaut
    Bonjour,

    je veus afficher tous les item de fichier xml
    mais mon application n'affiche Rien et merciiiiiiii
    Déjà en premier lieu
    http://nbenbourahla.developpez.com/t...s-application/

    Essaye de mettre des logs dans ton programme ou débogue le , cela aidera tout le monde pour savoir ce qui se passe dans ton application .

  3. #3
    Expert confirmé

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Billets dans le blog
    3
    Par défaut
    Marrant... SitesList est à l'inverse complet de ce qu'il faut faire, à savoir, un objet "SiteData" et maintenir une ArrayList<SiteData>....

    Que se passe-t-il si les les listes à l'interieur de SitesList n'ont pas la même taille ? hein ?
    C'est d'ailleurs le cas si il manque une valeur dans le fichier XML d'après ton code...

    Ensuite a l'affichage, tu ne met à jour qu'un seul groupe de text-view (il n'y aura donc pas de liste, et seul le dernier "Site" sera affiché).
    Si tu parles bien de ListView, alors il faut passer par un widget "ListView" et lui passer un Adapter (ArrayAdapter<SiteData> aurait bien marché, mais dans ton cas ca va être plus compliqué).

  4. #4
    Membre averti
    Homme Profil pro
    Etudiant
    Inscrit en
    Décembre 2011
    Messages
    9
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiant
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Décembre 2011
    Messages : 9
    Par défaut
    salut
    @ nicroman oui ma solution est très complexe, pour cela j'ai trouvé une autre solution et elle fonctionne correctement. Sauf que je veux ajouter un ratingbar dynamique de manière à ce que la valeur de la balise "id" de mon fichier xml, alimente le ratingbar.

    Si id=1, je trouve 1 étoile au niveau de ratingbar
    Si id=2, je trouve 2 etoile au niveau de ratingbar ...

    mon problème est au niveau de la class Main.java
    merciiiiiiii

    voilà mon fichier Xml à parser
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <results count="3">
    <result>
    <id>1</id>
    <name>mouradi</name>
    <score>234</score>
    </result>
    <result>
    <id>2</id>
    <name>aan</name>
    <score>2343</score>
    </result>
    voila mes layoute
    listeplacerholde.xml
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">	
     
        <ListView
    	 	android:id="@id/android:list"
    	    android:layout_width="fill_parent"
    	    android:layout_height="wrap_content"
    	    android:layout_weight="1"
    	 	android:drawSelectorOnTop="false" />
     
        <TextView
            android:id="@id/android:empty"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="No data"/>
     
    </LinearLayout>

    main.xml
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
     
     
     
     
     
     
     
     <ImageView
         android:id="@+id/img"
         android:contentDescription="@string/desc"
         android:layout_width="70dp"
         android:layout_height="96dp"
         android:padding="10dip" />
     
     
        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/i"
            android:layout_width="216dp"
            android:layout_height="123dp"
            android:orientation="vertical"
            android:paddingLeft="10dip" >
     
     
            <TextView
                android:id="@+id/item_title"
                android:layout_width="160dp"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textSize="20dp" />
     
     
            <TextView
                android:id="@+id/item_subtitle"
                android:layout_width="157dp"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textSize="13dp" />
     
     
     
     
     
            <TextView
                android:id="@+id/item_su"
                android:layout_width="158dp"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textSize="13dp" />
     
     
     
     
            <RatingBar
                android:id="@+id/rating"
                style="?android:attr/ratingBarStyleSmall"
                android:layout_width="180dp"
                android:layout_height="wrap_content"
                android:numStars="5"
                android:stepSize="1" />
     
        </LinearLayout>
     
    </LinearLayout>
    voila mes fonction java
    Main.java


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    package com.pxr.tutorial.xmltest;
     
    import java.util.ArrayList;
    import java.util.HashMap;
     
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
     
     
     
     
     
    import android.app.ListActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    //import android.widget.RatingBar;
    import android.widget.SimpleAdapter;
    import android.widget.Toast;
     
    public class Main extends ListActivity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.listplaceholder);
     
            ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
     
     
            String xml = XMLfunctions.getXML();
            Document doc = XMLfunctions.XMLfromString(xml);
     
            int numResults = XMLfunctions.numResults(doc);
     
            if((numResults <= 0)){
            	Toast.makeText(Main.this, "pas de resultas", Toast.LENGTH_LONG).show();  
            	finish();
            }
     
    		NodeList nodes = doc.getElementsByTagName("result");
     
    		for (int i = 0; i < nodes.getLength(); i++) {							
    			HashMap<String, String> map = new HashMap<String, String>();	
     
    			Element e = (Element)nodes.item(i);
    			map.put("id", XMLfunctions.getValue(e, "id"));
            	map.put("name", "nom:" + XMLfunctions.getValue(e, "name"));
            	map.put("Score", "Score: " + XMLfunctions.getValue(e, "score"));
     
            	mylist.add(map);			
    		}		
     
            ListAdapter adapter = new SimpleAdapter(this,mylist,R.layout.main, 
                            new String[] {"name","Score"}, 
                            new int[] { R.id.item_title, R.id.item_subtitle});
            RatingBar stars=(RatingBar) findViewById(R.id.rating);
        	stars.setNumStars(5);
        	stars.setRating("id");/* au niveau de ce ligne eclipse m'afficher erreur suivante"the methode setrating(float) in the type ratingbar is not applicable for argument (string)**/
            setListAdapter(adapter);
     
     
        }
    }

    XMLfunction.java


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    package com.pxr.tutorial.xmltest;
     
    import java.io.IOException;
    import java.io.StringReader;
    import java.io.UnsupportedEncodingException;
    import java.net.MalformedURLException;
     
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
     
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
     
     
    public class XMLfunctions {
     
    	public final static Document XMLfromString(String xml){
     
    		Document doc = null;
     
    		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            try {
     
    			DocumentBuilder db = dbf.newDocumentBuilder();
     
    			InputSource is = new InputSource();
    	        is.setCharacterStream(new StringReader(xml));
    	        doc = db.parse(is); 
     
    		} catch (ParserConfigurationException e) {
    			System.out.println("XML parse error: " + e.getMessage());
    			return null;
    		} catch (SAXException e) {
    			System.out.println("Wrong XML file structure: " + e.getMessage());
                return null;
    		} catch (IOException e) {
    			System.out.println("I/O exeption: " + e.getMessage());
    			return null;
    		}
     
            return doc;
     
    	}
     
    	/** Returns element value
              * @param elem element (it is XML tag)
              * @return Element value otherwise empty String
              */
    	 public final static String getElementValue( Node elem ) {
    	     Node kid;
    	     if( elem != null){
    	         if (elem.hasChildNodes()){
    	             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
    	                 if( kid.getNodeType() == Node.TEXT_NODE  ){
    	                     return kid.getNodeValue();
    	                 }
    	             }
    	         }
    	     }
    	     return "";
    	 }
     
    	 public static String getXML(){	 
    			String line = null;
     
    			try {
     
    				DefaultHttpClient httpClient = new DefaultHttpClient();
    				HttpPost httpPost = new HttpPost("http://testandroid.hebergratuit.com/bb.xml");
     
    				HttpResponse httpResponse = httpClient.execute(httpPost);
    				HttpEntity httpEntity = httpResponse.getEntity();
    				line = EntityUtils.toString(httpEntity);
     
    			} catch (UnsupportedEncodingException e) {
    				line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    			} catch (MalformedURLException e) {
    				line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    			} catch (IOException e) {
    				line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    			}
     
    			return line;
     
    	}
     
    	public static int numResults(Document doc){		
    		Node results = doc.getDocumentElement();
    		int res = -1;
     
    		try{
    			res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
    		}catch(Exception e ){
    			res = -1;
    		}
     
    		return res;
    	}
     
    	public static String getValue(Element item, String str) {		
    		NodeList n = item.getElementsByTagName(str);		
    		return XMLfunctions.getElementValue(n.item(0));
    	}
    }

Discussions similaires

  1. parser fichier xml
    Par debutant_linux dans le forum Ruby on Rails
    Réponses: 1
    Dernier message: 24/10/2007, 18h44
  2. [glib] parser fichier xml
    Par .:dev:. dans le forum C
    Réponses: 10
    Dernier message: 18/07/2006, 00h00
  3. [DOM] Erreur parser fichier xml avec caractère spéciaux
    Par turcotm dans le forum Format d'échange (XML, JSON...)
    Réponses: 4
    Dernier message: 19/06/2006, 09h01
  4. [XML] [EXPAT] Parser fichier XML
    Par Ben42 dans le forum Bibliothèques et frameworks
    Réponses: 12
    Dernier message: 17/02/2006, 14h08
  5. [XSL] Parser fichier xml : erreurs + incompréhensions
    Par totobouchon dans le forum Bibliothèques et frameworks
    Réponses: 1
    Dernier message: 19/07/2005, 15h47

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo