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 un fichier XML complexe


Sujet :

Android

  1. #1
    Membre habitué
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2010
    Messages
    164
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Maroc

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Octobre 2010
    Messages : 164
    Points : 159
    Points
    159
    Par défaut Parser un fichier XML complexe
    bonjour,


    je veux parser RSS du youtube, il est complexe je n'ai trouvé aucun tuto qui m'aidera à le parcourir, SVP aidé moi par un tuto

    merci

  2. #2
    Modérateur
    Avatar de wax78
    Homme Profil pro
    Chef programmeur
    Inscrit en
    Août 2006
    Messages
    4 086
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : Belgique

    Informations professionnelles :
    Activité : Chef programmeur
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2006
    Messages : 4 086
    Points : 7 997
    Points
    7 997

  3. #3
    Membre habitué
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2010
    Messages
    164
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Maroc

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Octobre 2010
    Messages : 164
    Points : 159
    Points
    159
    Par défaut
    merci pour les liens
    comment je peux faire avec un attribu comme "<media:group>"
    voici une partie du 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
    14
    15
    16
    17
    18
    19
    20
     
    <entry>
        <id>http://gdata.youtube.com/feeds/api/videos/9UTah0hW9nY</id>
        <published>2013-01-28T22:31:44.000Z</published>
        <updated>2013-01-29T05:26:06.000Z</updated>
        <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/>
        <category scheme='http://gdata.youtube.com/schemas/2007/categories.cat' term='Sports' label='Sport'/>
        <title type='text'>Football/CAN 2013: Ambiance de match Ghana - Niger à Abidjan</title>
        <content type='text'>Football/CAN 2013: Ambiance de match Ghana - Niger à Abidjan</content>
        <link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=9UTah0hW9nY&amp;feature=youtube_gdata'/>
        <link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/9UTah0hW9nY/responses'/>
        <link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/9UTah0hW9nY/related'/>
        <link rel='http://gdata.youtube.com/schemas/2007#mobile' type='text/html' href='http://m.youtube.com/details?v=9UTah0hW9nY'/>
        <link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/users/abidjannetTV/uploads/9UTah0hW9nY'/>
        <gd:comments>
          <gd:feedLink rel='http://gdata.youtube.com/schemas/2007#comments' href='http://gdata.youtube.com/feeds/api/videos/9UTah0hW9nY/comments' countHint='0'/>
        </gd:comments>
        <media:group>
          <media:category label='Sport' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Sports</media:category>
          <media:content url='http://www.youtube.com/v/9UTah0hW9nY?version=3&amp;f=user_uploads&amp;app=youtube_gdata' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='103' yt:format='5'/>

  4. #4
    Modérateur
    Avatar de wax78
    Homme Profil pro
    Chef programmeur
    Inscrit en
    Août 2006
    Messages
    4 086
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : Belgique

    Informations professionnelles :
    Activité : Chef programmeur
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2006
    Messages : 4 086
    Points : 7 997
    Points
    7 997
    Par défaut
    J'ai dut louper un truc, Comment faire quoi ?

  5. #5
    Modérateur

    Profil pro
    Inscrit en
    Septembre 2004
    Messages
    12 565
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 565
    Points : 21 631
    Points
    21 631
    Par défaut
    C'est un élément, pas un attribut. Tu auras toujours du mal si tu apprends pas d'abord le XML, et ensuite le truc à YouTube.

    Ensuite, se décider pour une API XML. Je recommande JDOM, de loin le plus simple.

    Ton problème ici c'est d'atteindre un élément muni d'un namespace, et je ne trouve pas tellement d'exemples avec JDOM sur le net. C'est évident pour qui connaît XML et les namespaces.

    Alors voici un exemple, en supposant que tu aies obtenu un Document comme indiqué dans le tutoriel JDOM et que tu aies obtenu l'Element entry :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    // Je le sors pas de mon chapeau : on le voit avec xmlns:media="http://search.yahoo.com/mrss/"
    final Namespace MEDIA_NS = Namespace.getNamespace("media", "http://search.yahoo.com/mrss/");
    Element group = entry.getChild("group", MEDIA_NS);

  6. #6
    Membre habitué
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2010
    Messages
    164
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Maroc

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Octobre 2010
    Messages : 164
    Points : 159
    Points
    159
    Par défaut
    merci pour vos aides
    mon problème c'était de pouvoir arrivée aux éléments
    voici le code si quelqu'un à le même besoin
    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
     
    public class XMLParsingDOMExample extends Activity {
     
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
     
    		/** Create a new layout to display the view */
    		LinearLayout layout = new LinearLayout(this);
    		layout.setOrientation(1);
     
    		/** Create a new textview array to display the results */
    		TextView name[];
    		TextView website[];
    		TextView category[];
     
    		try {
     
    			URL url = new URL("http://gdata.youtube.com/feeds/api/users/abidjannetTV/uploads?orderby=updated");
    			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    			DocumentBuilder db = dbf.newDocumentBuilder();
    			Document doc = db.parse(new InputSource(url.openStream()));
    			doc.getDocumentElement().normalize();
     
    			NodeList nodeList = doc.getElementsByTagName("entry");
     
    			/** Assign textview array lenght by arraylist size */
    			name = new TextView[nodeList.getLength()];
    			website = new TextView[nodeList.getLength()];
    			category = new TextView[nodeList.getLength()];
     
    			for (int i = 0; i < nodeList.getLength(); i++) {
     
    				Node node = nodeList.item(i);
     
    				name[i] = new TextView(this);
    				website[i] = new TextView(this);
    				category[i] = new TextView(this);
     
    				Element fstElmnt = (Element) node;
    				NodeList nameList = fstElmnt.getElementsByTagName("title");
    				Element nameElement = (Element) nameList.item(0);
    				nameList = nameElement.getChildNodes();
    				name[i].setText("title = "
    						+ ((Node) nameList.item(0)).getNodeValue());
     
    				NodeList websiteList = fstElmnt.getElementsByTagName("media:content");
    				Element websiteElement = (Element) websiteList.item(0);
    				websiteList = websiteElement.getChildNodes();
    //				website[i].setText("Website = "
    //						+ ((Node) websiteList.item(0)).getNodeValue());
     
    				String f = websiteElement.getAttribute("yt:format");
    				if(f.equals("5")){
    					website[i].setText("type = " + websiteElement.getAttribute("type"));
    				}
     
    				NodeList nodeList2 = doc.getElementsByTagName("author");
    				for (int j = 0; j < nodeList2.getLength(); j++) {
    					Node node2 = nodeList.item(i);
    					Element autElmnt2 = (Element) node2;
    					NodeList autList = autElmnt2.getElementsByTagName("name");
    					Element autElement = (Element) autList.item(0);
    					nameList = autElement.getChildNodes();
    					category[i].setText("autor name = "
    							+ ((Node) nameList.item(0)).getNodeValue());
    				}
     
     
    				layout.addView(name[i]);
    				layout.addView(website[i]);
    				layout.addView(category[i]);
     
    			}
    		} catch (Exception e) {
    			System.out.println("XML Pasing Excpetion = " + e);
    		}
     
    		/** Set the layout view to display */
    		setContentView(layout);
     
    	}
    }

  7. #7
    Modérateur

    Profil pro
    Inscrit en
    Septembre 2004
    Messages
    12 565
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 565
    Points : 21 631
    Points
    21 631
    Par défaut
    Ouais, enfin, quitte à donner un exemple, ça aurait pas été plus mal de donner juste ce qui a un rapport avec XML.
    Par ailleurs cet exemple ignore totalement les namespaces. Ce n'est sans doute pas bien grave avec cette API YouTube, mais c'est à éviter en principe : les namespaces ne sont absolument pas facultatifs.

    Enfin, ça utilise l'API DOM fournie avec Java, qui est excessivement compliquée. Je recommande plutôt JDOM.
    Voici la même chose, qui se concentre uniquement sur le XML, avec JDOM, et tenant compte des namespaces :

    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
    public class VideoInfoExtract {
     
      public static final Namespace ATOM_NS = Namespace.getNamespace("http://www.w3.org/2005/Atom");
      public static final Namespace MEDIA_NS = Namespace.getNamespace("media", "http://search.yahoo.com/mrss/");
      public static final Namespace YOUTUBE_NS = Namespace.getNamespace("yt", "http://gdata.youtube.com/schemas/2007");
     
      public static class VideoInfo {
        public final String name;
        public final String type;
        public final String author;
        public VideoInfo(String name, String type, String author) {
          this.name = name;
          this.type = type;
          this.author = author;
        }
      }
     
      public static List<VideoInfo> extract(InputStream is) throws JDOMException, IOException {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(is);
     
        List<Element> entries = doc.getRootElement().getChildren("entry", ATOM_NS);
        int nbEntries = entries.size(); // pas utile mais on peut l'avoir
        List<VideoInfo> infos = new ArrayList<VideoInfo>(nbEntries);
     
        for(Element entry : entries) {
          String name = entry.getChildText("title", ATOM_NS);
     
          String author = entry.getChild("author", ATOM_NS).getChildText("name", ATOM_NS);
     
          XPathBuilder<Element> typePathBuilder
            = new XPathBuilder<Element>("media:group/media:content[@yt:format = '5']", Filters.element());
          typePathBuilder.setNamespace(MEDIA_NS);
          typePathBuilder.setNamespace(YOUTUBE_NS);
          XPathExpression<Element> typePath = typePathBuilder.compileWith(XPathFactory.instance());
     
          String type = typePath.evaluateFirst(entry).getAttributeValue("type");
     
          infos.add(new VideoInfo(name, type, author));
        }
     
        return infos;
      }
     
    }

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. parser un fichier xml complexe.
    Par Smix007 dans le forum C#
    Réponses: 2
    Dernier message: 09/02/2010, 17h41
  2. [xslt] Parser 2 fichiers XML
    Par malekms dans le forum XSL/XSLT/XPATH
    Réponses: 4
    Dernier message: 30/12/2005, 12h22
  3. Parser un fichier XML
    Par Charlinecha dans le forum Format d'échange (XML, JSON...)
    Réponses: 1
    Dernier message: 11/07/2005, 17h18
  4. [SAX] parser un fichier xml en Java
    Par royou dans le forum Format d'échange (XML, JSON...)
    Réponses: 1
    Dernier message: 10/02/2005, 17h12
  5. parser des fichier .xml en perl
    Par djibril dans le forum Modules
    Réponses: 13
    Dernier message: 18/05/2004, 17h08

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