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

Java Discussion :

Modifier le contenu d'une balise


Sujet :

Java

  1. #1
    Membre averti
    Femme Profil pro
    Étudiant
    Inscrit en
    Décembre 2011
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

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

    Informations forums :
    Inscription : Décembre 2011
    Messages : 18
    Par défaut Modifier le contenu d'une balise
    Bonjour
    sa fait plus qu'un mois que je me suis bloqué à ce niveau
    mon but est modifier le contenu d'un fichier.ce changement consiste à lire et écrire le fichier simultanément afin de changer le contenu.
    Exemple :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    <solution>intent:</solution>contenu1 à ajouter ( paragraph ou phrase ou Text...)
    <identification>first Name:</identification>contenu2 à ajouter ( paragraph ou phrase ou Text...)
    <guidance>manag :</guidance>contenu3 à ajouter ( paragraph ou phrase ou Text...)
    mon but est de structurer le meme fichier afin de le rendre:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    <solution>contenu1 à ajouter ( paragraph ou phrase ou Text...)</solution>
    <identification>contenu2 à ajouter ( paragraph ou phrase ou Text...)</identification>
    <guidance>contenu3 à ajouter ( paragraph ou phrase ou Text...)</guidance>

  2. #2
    Modérateur

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

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 586
    Par défaut
    Faudrait nous parler un peu de ce que tu as essayé de faire.
    Pas envie de juste faire ton programme à ta place.
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  3. #3
    Membre averti
    Femme Profil pro
    Étudiant
    Inscrit en
    Décembre 2011
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

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

    Informations forums :
    Inscription : Décembre 2011
    Messages : 18
    Par défaut
    j'ai pas pu coder mes idées
    j'ai essayé de lire le fichier et d'ecrire dans un fichier temporaire afin mais le problème réside du faite que j'arrive pas à faire une lecture et écriture conditionelles
    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
     
               File entree = new File("D://fich.xml");
               File sortie = new File("D://temp.txt");
               BufferedReader br = new BufferedReader(new FileReader(entree));
               BufferedWriter bw = new BufferedWriter(new FileWriter(sortie));
               String ligne="";
               while ((ligne = br.readLine()) != null)
               {
                   StringTokenizer st = new StringTokenizer(ligne);
                    while(st.hasMoreTokens())
                    {
                        String chaine="<problem>";
                        if(st.nextToken().equals(chaine))
                        {
                            bw.write(chaine);
     
                        }
                    }
               }

  4. #4
    Modérateur

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

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 586
    Par défaut
    Hum, mais sans parler du code Java, la méthode que tu emploierais, c'est quoi ?
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  5. #5
    Membre averti
    Femme Profil pro
    Étudiant
    Inscrit en
    Décembre 2011
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

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

    Informations forums :
    Inscription : Décembre 2011
    Messages : 18
    Par défaut
    Bonjour
    j'ai besoin d'une méthode qui me permet de modifier un fichier afin de deplacer une paragraphe à la place d'une autre.

  6. #6
    Membre averti
    Femme Profil pro
    Étudiant
    Inscrit en
    Décembre 2011
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

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

    Informations forums :
    Inscription : Décembre 2011
    Messages : 18
    Par défaut
    l'idée est de parcourir le fichier et dés qu'on détecte une balise ( <solution> par exemple ),on récupère le texte qui existe just aprés la balise jusqu'à un autre balise et on met ce paragraphe dans le contenu de la balise précédente.

  7. #7
    Modérateur

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

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 586
    Par défaut
    Hum. Et tout ça peut être sur plusieurs lignes ou une seule ligne ?
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  8. #8
    Membre averti
    Femme Profil pro
    Étudiant
    Inscrit en
    Décembre 2011
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

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

    Informations forums :
    Inscription : Décembre 2011
    Messages : 18
    Par défaut
    oui sa peut etre sur plusieurs lignes
    voici un exemple de fichier en entréé
    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
     
    <html>
    Business Architecture 
    <InitialContext>Context:</InitialContext> 
    You are building a system which will need to inter-operate with other applications within your enterprise. 
    <Problem>Problem:</Problem> 
    How can you make sure that all the applications in your enterprise can inter-operate properly? 
    <Force>Forces:</Force> 
    There are many entities in the typical business and relationships amongst them that can be quite complex. 
    If each application defines its own entities, the applications will not share a common vocabulary. 
    Even if they work from the same domain model but each application creates its own implementations of the entities, the applications will be hard pressed to inter-operate. 
    (The so-called “application silo” problem.) 
    Every business process (or the software application which implements it) may introduce additional associations between existing objects (what kind of relationships 
    to what kind of objects?). Left unmanaged, this can create overly complex relationships which make persistence design (amongst others)(Do these unmanaged relationships only impact persistence design or is it just an example?) very difficult. 
    Someone needs to be responsible for monitoring proposed new business objects (entities) for commonality with already defined ones. Once identified, it may be necessary to reconcile differences in attributes or naming, and to introduce new abstractions to capture the commonality where there are significant legitimate differences. 
    Many developers look for differences rather than for similarities. This is then used to justify why they cannot reuse (with or without modification) the existing concepts. 
    <Solution>Solution:</Solution> 
    Define a Business Architecture based on the structure of the business. The business architecture defines the vocabulary of the business to ensure that all applications mean the same thing when they use a particular noun. 
    Assign an Architect (or ArchitectureTeam) to own it. (ArtifactOwner) Validate it using the BusinessUseCases which capture the BusinessProcesses. The Business Architecture will describe the BusinessObjects in your domain complete with all the operations (including attributes) they support and the associations they may have with other BusinessObjects 
    <ResultingContext>Resulting Context:</ResultingContext> 
    The Business Objects may become quite large due the varied requirements of the many applications which use them. You may find it necessary to use Business Object Extensions2 to add the additional behavior and attributes which are only required by some Business Processes. 
    <RelatedPattern>Related Patterns:</RelatedPattern> 
    ArtifactOwner [Cope95] states that any artifact which is considered valuable must have an owner who is assigned the responsibility for maintaining its integrity (otherwise it is sure to lose its value over time.) 
    <Application>Implementation:</Application> 
    When you get to the point of implementing your system, all your Business Objects should inherit their basic implementation from a single class. This class would be a good place to add the interface which allows all Business Objects to support Transactions and Persistence. The implementation of this interface would use the services of the Technical Infrastructure. 
    If you need to inter-operate with systems of other companies, you may need to jointly 
    define an IndustryArchitecture which consists of the definitions of common concepts in the industry. The OMG has established a number of such groups for the purpose of 
    standardizing on a set of common Business Objects across a particular industry. 
    </html>
    le fichier en sortie doit être
    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
     
    <html>
    Business Architecture 
    <InitialContext>You are building a system which will need to inter-operate with other applications within your enterprise. :</InitialContext> 
    <Problem>How can you make sure that all the applications in your enterprise can inter-operate properly? </Problem> 
    <Force>There are many entities in the typical business and relationships amongst them that can be quite complex. 
    If each application defines its own entities, the applications will not share a common vocabulary. 
    Even if they work from the same domain model but each application creates its own implementations of the entities, the applications will be hard pressed to inter-operate. 
    (The so-called “application silo” problem.) 
    Every business process (or the software application which implements it) may introduce additional associations between existing objects (what kind of relationships 
    to what kind of objects?). Left unmanaged, this can create overly complex relationships which make persistence design (amongst others)(Do these unmanaged relationships only impact persistence design or is it just an example?) very difficult. 
    Someone needs to be responsible for monitoring proposed new business objects (entities) for commonality with already defined ones. Once identified, it may be necessary to reconcile differences in attributes or naming, and to introduce new abstractions to capture the commonality where there are significant legitimate differences. 
    Many developers look for differences rather than for similarities. This is then used to justify why they cannot reuse (with or without modification) the existing concepts. 
    </Force> 
    <Solution>Define a Business Architecture based on the structure of the business. The business architecture defines the vocabulary of the business to ensure that all applications mean the same thing when they use a particular noun. 
    Assign an Architect (or ArchitectureTeam) to own it. (ArtifactOwner) Validate it using the BusinessUseCases which capture the BusinessProcesses. The Business Architecture will describe the BusinessObjects in your domain complete with all the operations (including attributes) they support and the associations they may have with other BusinessObjects 
    </Solution> 
    <ResultingContext>The Business Objects may become quite large due the varied requirements of the many applications which use them. You may find it necessary to use Business Object Extensions2 to add the additional behavior and attributes which are only required by some Business Processes. 
    </ResultingContext> 
    <RelatedPattern>ArtifactOwner [Cope95] states that any artifact which is considered valuable must have an owner who is assigned the responsibility for maintaining its integrity (otherwise it is sure to lose its value over time.) 
    </RelatedPattern> 
    <Application>When you get to the point of implementing your system, all your Business Objects should inherit their basic implementation from a single class. This class would be a good place to add the interface which allows all Business Objects to support Transactions and Persistence. The implementation of this interface would use the services of the Technical Infrastructure. 
    If you need to inter-operate with systems of other companies, you may need to jointly 
    define an IndustryArchitecture which consists of the definitions of common concepts in the industry. The OMG has established a number of such groups for the purpose of 
    standardizing on a set of common Business Objects across a particular industry. </Application> 
     
    </html>

  9. #9
    Membre averti
    Femme Profil pro
    Étudiant
    Inscrit en
    Décembre 2011
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

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

    Informations forums :
    Inscription : Décembre 2011
    Messages : 18
    Par défaut
    j'ai essayé ce code mais sa marche pas encore
    j'ai essayé de tester les 2 premières balises mais sa marche pas
    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
     
     public void modifier()
        {
           try
           {
               File entree = new File("D://fich.xml");
               File sortie = new File("D://temp.xml");
               BufferedReader br = new BufferedReader(new FileReader(entree));
               BufferedWriter bw = new BufferedWriter(new FileWriter(sortie));
               String ligne="";
               String ligne2="";
               while ((ligne = br.readLine()) != null)
               {
                   ligne=ligne2;
                   StringTokenizer st = new StringTokenizer(ligne);
                   System.err.print("avant if");
                   String chaine1="<InitialContext>";
                   String [] var = null;
                   int i=0;
                   while(st.hasMoreTokens())
                   {
                      var[i]=st.nextToken();
                      System.err.print(var[i]);
                   }
     
                  if(var[0].equals(chaine1))
                  {
                        ligne2=br.readLine();
                      System.err.print("entré if initial context");
                      bw.write("<InitialContext>");
                      while(((ligne2.startsWith("<Problem>"))== false) && ((ligne2.startsWith("<InitialContext>"))== false))
                       {
                               bw.write(st.nextToken()+" ");
                                bw.newLine();
                       }
                      bw.write("</InitialContext>");
                  }
                  else
                  {
                       bw.write(ligne);
                       bw.newLine();
     
                  }
     
               }
               br.close();
               bw.close();
     
     
        }
           catch(Exception e)
           {
               e.getMessage();
           }
        }

  10. #10
    Modérateur

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

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 586
    Par défaut
    Dire "ça ne marche pas" est inutile. Il faut décrire ce qui est réussi et ce qui est raté.

    C'est un problème un peu complexe. Si par hasard c'est vraiment du XML, ça te simplifierait la vie d'utiliser plutôt JDOM, ou au moins un parseur SAX, qui se chargeront à ta place d'identifier où commencent et s'arrêtent les balises.
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  11. #11
    Membre averti
    Femme Profil pro
    Étudiant
    Inscrit en
    Décembre 2011
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

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

    Informations forums :
    Inscription : Décembre 2011
    Messages : 18
    Par défaut
    BJR
    j'ai remarqué qu'au niveau de la compilation,le problème réside au niveau de ''if''
    car sinn ''else'' est éxécuté sans problem !! j'ai pas arriver à identifier l'erreur.
    sinon concernant l'utilisation de DOM w n'importe quel parser XML,j'ai pensé à cet API mais le problem qu'il considère seulement le contenu entre balises et ignore l'autre alors que mon problem et de copier le contenu hors balises dans les balises convenables !!
    merci encore une autre fois

  12. #12
    Modérateur

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

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 586
    Par défaut
    Citation Envoyé par khouloudmad Voir le message
    sinon concernant l'utilisation de DOM w n'importe quel parser XML,j'ai pensé à cet API mais le problem qu'il considère seulement le contenu entre balises et ignore l'autre
    Pas du tout. Mais, il faut apprendre à s'en servir, c'est sûr.
    À mon avis c'est plus simple avec un parseur déjà fait.

    Et je ne comprends toujours pas ce que tu essayais de faire avec le code que tu nous montres. C'est pourtant pas faute d'avoir demandé.
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  13. #13
    Membre averti
    Femme Profil pro
    Étudiant
    Inscrit en
    Décembre 2011
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

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

    Informations forums :
    Inscription : Décembre 2011
    Messages : 18
    Par défaut
    avec ce code ,j'ai pensé à récupérer la nature de la balise en premier lieu,puis le contenu souhaité en deuxième lieu !!
    par exemple j'ai essayé d'ecrire dans un fichier temporaire l'ouverture de la balise <initialcontext> puis j'ai essayé d'accéder au contenu souahaité afin de le mettre juste aprés l'ouverture de la balise.

    concernant un parser ,je me demande si vous etes sur que c'est fesable avec cet API ? (l'accés au contenu qui n'appartient pas à une balise ?)

  14. #14
    Modérateur

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

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 586
    Par défaut
    Citation Envoyé par khouloudmad Voir le message
    avec ce code ,j'ai pensé à récupérer la nature de la balise en premier lieu,puis le contenu souhaité en deuxième lieu !!
    par exemple j'ai essayé d'ecrire dans un fichier temporaire l'ouverture de la balise <initialcontext> puis j'ai essayé d'accéder au contenu souahaité afin de le mettre juste aprés l'ouverture de la balise.
    Oui. Et en détail, comment se repère tout ça ? Parce que le code Java n'a pas du tout l'air de faire ce genre de choses.

    Citation Envoyé par khouloudmad Voir le message
    concernant un parser ,je me demande si vous etes sur que c'est fesable avec cet API ? (l'accés au contenu qui n'appartient pas à une balise ?)
    De toute façon, le contenu appartient à la balise <html> -_-°.

    Fondamentalement,
    - en SAX il s'agit de lire le texte qui se trouve après une balise fermante et avant la prochaine balise ouvrante.
    - en JDOM il s'agit le lire le texte qui est un nœud frère de l'élément et qui est situé juste après.
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  15. #15
    Membre averti
    Femme Profil pro
    Étudiant
    Inscrit en
    Décembre 2011
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

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

    Informations forums :
    Inscription : Décembre 2011
    Messages : 18
    Par défaut
    SVP pouvez vous me fournir un exemple de code ( utilisation de JDOM ou SAX) qui peux m'aider ?
    Merci

  16. #16
    Modérateur

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

    Informations forums :
    Inscription : Septembre 2004
    Messages : 12 586
    Par défaut
    Example JDOM :

    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
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(xmlFile);
    List<Content> content = new ArrayList<Content>();
    content.addAll(doc.getRootElement().getContent());
     
    ListIterator<Content> itr = content.listIterator();
    while(itr.hasNext()) {
      Content node = itr.next();
      if(node instanceof Element) {
        Element element = (Element)node;
        System.out.format("Element <%s>\n", element.getName());
     
        Content next = itr.next();
        if(next instanceof Text) {
          System.out.format("Texte détecté : >%s<\n", next.getValue());
        } else {
          System.out.format("Pas de texte après\n");
          // faire comme si on n'avait pas fait le dernier next()
          itr.previous();
        }
      }
    }
    Cela analyse les éléments d'un fichier XML, et quand il y a un texte entre deux éléments, il l'affiche.

    En fait, ce serait peut-être plus simple avec des expressions XPath, qui a des commandes pour accéder au nœud frère suivant un élément. Mais, il faut être à l'aise avec XPath.
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  17. #17
    Membre averti
    Femme Profil pro
    Étudiant
    Inscrit en
    Décembre 2011
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

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

    Informations forums :
    Inscription : Décembre 2011
    Messages : 18
    Par défaut
    bjr
    j'ai essayé ce code mais il m'affiche cette exception
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    org.jdom2.ContentList cannot be cast to javax.swing.text.AbstractDocument$Content
    malgré que j'ai changé le code
    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
     public void affContenu() throws Exception
     
        {
            File fich = new File("D:\\fich.xml");
            SAXBuilder builder = new SAXBuilder();
            org.jdom2.Document doc = builder.build(fich);
          List<Content> content = new ArrayList<Content>();
          content.add((Content) doc.getRootElement().getContent());
         // content.addAll(doc.getRootElement().getContent());
     
          ListIterator<Content> itr = content.listIterator();
          while(itr.hasNext())
          {
            Content node = itr.next();
            if(node instanceof Element) {
            Element element = (Element)node;
            System.out.format("Element <%s>\n", element.getSimpleName());
           Content next = itr.next();
            if(next instanceof Text)
            {
              System.out.format("Texte détecté : >%s<\n", next.toString());
            }
            else
            {
                 System.out.format("Pas de texte après\n");
                 // faire comme si on n'avait pas fait le dernier next()
                 itr.previous();
            }
      }
    }

Discussions similaires

  1. modifier le contenu d'une balise object
    Par ygeronimi dans le forum Général JavaScript
    Réponses: 1
    Dernier message: 15/10/2013, 09h22
  2. modifier le contenu d'une balise.
    Par isabelle22 dans le forum Général JavaScript
    Réponses: 5
    Dernier message: 31/01/2010, 16h59
  3. Réponses: 12
    Dernier message: 20/09/2006, 10h31
  4. [Upload] Modifier le contenu d'une liste box automatiquemen
    Par Phenomenium dans le forum Langage
    Réponses: 7
    Dernier message: 16/01/2006, 22h42
  5. modifier le contenu d'une table avec innerHTML
    Par francon81 dans le forum Général JavaScript
    Réponses: 8
    Dernier message: 31/05/2005, 10h02

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