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

VB.NET Discussion :

convertir un xml en txt [Débutant]


Sujet :

VB.NET

  1. #1
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    59
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2003
    Messages : 59
    Points : 31
    Points
    31
    Par défaut convertir un xml en txt
    Bonsoir à tous !

    Je débute dans le xml et je n'ai pas une grosse expérience en vb.net mais je voudrais convertir un fichier xml en fichier txt formaté d'une certaine façon.
    voici par exemple mon fichier xml :test_xml_to_asc.xml

    transformer de la sorte dans un fichier txt

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
    cue  "<number> du xml"
    up    "<cuepart><basic_fade>" du xml
    chan  "<channel_id>"/"<value>"   "<channel_id>"/"<value>"   "<channel_id>"/"<value>"  
    chan  "<channel_id>"/"<value>"   "<channel_id>"/"<value>"   "<channel_id>"/"<value>" 
    ...
     
    cue  "<number> du xml"
    up    "<cuepart><basic_fade>" du xml
    chan  "<channel_id>"/"<value>"   "<channel_id>"/"<value>"   "<channel_id>"/"<value>"
    chan  "<channel_id>"/"<value>"   "<channel_id>"/"<value>"   "<channel_id>"/"<value>" 
    ...
     
    et ça pour chaque cue du xml
    Je ne sais pas si je suis très clair et si je post au bon endroit mais si vous voulez d'autres explications demander moi !

    D'avance merci

  2. #2
    Membre éprouvé
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    665
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 665
    Points : 1 161
    Points
    1 161
    Par défaut
    Bonsoir,
    voici une première approche pour appréhender l'arborescence d'un 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
    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
        Dim xmlFilePath As String = IO.Directory.GetCurrentDirectory & "\test_xml_to_asc.xml" ' Chemin du fichier .XML
        Dim strgBuilt As New System.Text.StringBuilder  'Stockage temporaire des chaines
        Dim txtFilePath As String = IO.Directory.GetCurrentDirectory & "\test.txt"  'Chemin du fichier .txt
     
        Private Sub ExtractFileXml(ByVal fichier As String)
     
            'Charge le fichier xml.
            Dim xmldoc As New XmlDocument()
            xmldoc.Load(fichier)
     
            'Liste les éléments qui correspondent à "Cue"
            Dim Cues As XmlNodeList
            Cues = xmldoc.GetElementsByTagName("Cue")
     
            'Liste les enfants de chaque "Cue"
            For Each Cue As XmlNode In Cues
                Dim CueShildNodes As XmlNodeList = Cue.ChildNodes
     
                'Recherche "number" et l'enregistre dans un StringBuilder
                For i As Integer = 0 To CueShildNodes.Count - 1
                    Dim CueShildNode As XmlNode = CueShildNodes(i)
                    If CueShildNode.Name = "Number" Then
                        strgBuilt.Append("cue : " & CueShildNode.Attributes.ItemOf("number").Value)
                        strgBuilt.AppendLine()
                    End If
                Next
     
                'Idem pour "basic_fade"
                For i As Integer = 0 To CueShildNodes.Count - 1
                    Dim CueShildNode As XmlNode = CueShildNodes(i)
                    If CueShildNode.Name = "CuePart" Then
                        strgBuilt.Append("up : " & CueShildNode.Attributes.ItemOf("basic_fade").Value)
                        strgBuilt.AppendLine()
                    End If
                Next
     
                'Même démarche pour les enfants des enfants de "CueDatas"
                For i As Integer = 0 To CueShildNodes.Count - 1
                    Dim CueShildNode As XmlNode = CueShildNodes(i)
                    If CueShildNode.Name = "CueDatas" Then
                        Dim CueDatasShildNodes As XmlNodeList = CueShildNode.ChildNodes
                        For Each CueDatasShildNode As XmlElement In CueDatasShildNodes
                            For j As Integer = 0 To 1
                                If CueDatasShildNode.ChildNodes(j).Name = "Channel" Then
                                    strgBuilt.Append("chan : " & CueDatasShildNode.ChildNodes(j).Attributes.ItemOf("channel_id").Value)
                                End If
                                If CueDatasShildNode.ChildNodes(j).Name = "Value" Then
                                    strgBuilt.Append("  " & CueDatasShildNode.ChildNodes(j).InnerText)
                                    strgBuilt.AppendLine()
                                End If
                            Next
                        Next
                    End If
                Next
                strgBuilt.AppendLine()
            Next
     
                SaveToFile(txtFilePath)
        End Sub
     
     
        Private Sub SaveToFile(ByVal fileName As String)
     
            Dim w As System.IO.TextWriter = New System.IO.StreamWriter(fileName)
            w.Write(strgBuilt.ToString())
            w.Flush()
            w.Close()
     
        End Sub
     
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            ExtractFileXml(xmlFilePath)
        End Sub

  3. #3
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    59
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2003
    Messages : 59
    Points : 31
    Points
    31
    Par défaut
    Merci de m'avoir répondu chrismonoye.

    ça à l'air prometteur mais je n'ai pas le temps de tester ton code en ce moment (beaucoup de travail), je pourrais le faire en début de semaine prochaine.

  4. #4
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    59
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2003
    Messages : 59
    Points : 31
    Points
    31
    Par défaut
    J'ai testé le code de chrismonoye et c'est ce que je voulais faire, mais je dois apporter quelques modifications.
    Je voudrais testé si l'attribut "name" dans le noeud "cuepart" existe pour ensuite l’intégrer dans le fichier texte comme ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    cue  "<number> du xml"
    up    "<cuepart><basic_fade>" du xml
    TEXT  "name" du xml
    chan  "<channel_id>"/"<value>"   "<channel_id>"/"<value>"   "<channel_id>"/"<value>"  
    chan  "<channel_id>"/"<value>"   "<channel_id>"/"<value>"   "<channel_id>"/"<value>" 
    ...
    j'ai fait des essais mais je n'y arrive pas.

    D'avance merci.

  5. #5
    Membre éprouvé
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    665
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 665
    Points : 1 161
    Points
    1 161
    Par défaut
    Bonjour,
    tester si l'attribut voulu du nœud existe genre :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    If CueShildNode.Name = "CuePart" AndAlso CueShildNode.Attributes("name") IsNot Nothing Then

  6. #6
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    59
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2003
    Messages : 59
    Points : 31
    Points
    31
    Par défaut
    Merci c'est ce que je voulais faire.

    J'ai intégré ton code et je suis a nouveau bloqué.

    voila ce que j'ai mis :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
                For i As Integer = 0 To CueShildNodes.Count - 1
                    Dim CueShildNode As XmlNode = CueShildNodes(i)
     
                    If CueShildNode.Name = "CuePart" AndAlso CueShildNode.Attributes("name") IsNot Nothing Then
                        strgBuilt.Append("TEXT " & CueShildNode.Attributes.ItemOf("name").Value)
                        strgBuilt.AppendLine()
     
                    ElseIf CueShildNode.Name = "InfoItems" Then
                        strgBuilt.Append("TEXT " & CueShildNode.InnerText)
                        strgBuilt.AppendLine()
                    End If
     
                Next
    ça me met une ligne avec
    TEXT "texte du info de infoitem"
    puis une ligne avec
    TEXT "texte du cuepart name"

    mais ce que je veux c'est qu'une seule ligne TEXT avec "texte du cuepart name" ou "texte du info de infoitem" si "texte du cuepart n'existe pas.

    Vois tu l'erreur que j'ai faite ?

  7. #7
    Membre éprouvé
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    665
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 665
    Points : 1 161
    Points
    1 161
    Par défaut
    Bonjour,
    à première vue, le souci ne vient pas du bout de code que tu fournis.
    Il faudrait voir dans ton code si tu ne recherches pas deux fois "cuepart name".

  8. #8
    Membre éprouvé
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    665
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 665
    Points : 1 161
    Points
    1 161
    Par défaut
    Bonsoir,
    comme dit dans mon premier message, c'est une approche du XML, par le NameSpace System.Xml
    Pour de nombreuses requêtes, ce n'est guère satisfaisant.

    D'autres espaces de nom relatifs à Xml existent :

    System.Xml.XPath est une possibilité.
    Voici un exemple qui pourrait s'appliquer à ton cas :
    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
        Private Sub ExtractFileXmlXPath(ByVal fichier As String)
     
            'Navigation et itération dans le doc XML pour la récupération des éléments "Cue"
            Dim document As XPathDocument = New XPathDocument(fichier)
            Dim navigator As XPathNavigator = document.CreateNavigator()
            Dim nodesCue As XPathNodeIterator = navigator.Select("/MA/Sequ/Cue")
     
            While nodesCue.MoveNext()
                'Pour chaque éléments "cue", un autre navigateur permet d'extraire les infos recherchées.
                If nodesCue.Current.HasChildren Then
                    Dim nodesNavigator As XPathNavigator = nodesCue.Current.CreateNavigator
     
                    Dim cue As String = nodesNavigator.SelectSingleNode("Number").GetAttribute("number", nodesNavigator.NamespaceURI)
                    If Not cue = String.Empty Then
                        strgBuilt.Append("cue : " & cue)
                        strgBuilt.AppendLine()
                    End If
     
                    Dim up As String = nodesNavigator.SelectSingleNode("CuePart").GetAttribute("basic_fade", nodesNavigator.NamespaceURI)
                    If Not up = String.Empty Then
                        strgBuilt.Append("up : " & up)
                        strgBuilt.AppendLine()
                    End If
     
                    Dim txt As String = nodesNavigator.SelectSingleNode("CuePart").GetAttribute("name", nodesNavigator.NamespaceURI)
                    If Not txt = String.Empty Then
                        strgBuilt.Append("TEXT : " & txt)
                        strgBuilt.AppendLine()
                    Else : txt = nodesNavigator.SelectSingleNode("InfoItems").SelectSingleNode("Info").InnerXml
                        If Not txt = String.Empty Then
                            strgBuilt.Append("TEXT : " & txt)
                            strgBuilt.AppendLine()
                        End If
                    End If
     
                    'Même principe pour les noeuds aux enfants multiples.
                    Dim nodesCueDatas As XPathNodeIterator = nodesCue.Current.SelectDescendants("CueData", nodesNavigator.NamespaceURI, False)
                    While nodesCueDatas.MoveNext()
                        If nodesCueDatas.Current.HasChildren Then
                            Dim nodesCueDatasNavigator As XPathNavigator = nodesCueDatas.Current.CreateNavigator
     
                            Dim chan As String = nodesCueDatasNavigator.SelectSingleNode("Channel").GetAttribute("channel_id", nodesNavigator.NamespaceURI)
                            If Not chan = String.Empty Then
                                strgBuilt.Append("chan : " & chan)
                            End If
     
                            Dim valeur As String = nodesCueDatasNavigator.SelectSingleNode("Value").InnerXml
                            If Not valeur = String.Empty Then
                                strgBuilt.Append("    valeur : " & valeur)
                                strgBuilt.AppendLine()
                            End If
                        End If
                    End While
     
                    strgBuilt.AppendLine()
                End If
            End While
     
            SaveToFile(txtFilePath)
     
        End Sub
    System.Xml.Linq, en est une autre.
    Autre exemple applicable à ton 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
    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
        Private Sub ExtractFileXmlLinq(ByVal fichier As String)
     
            Dim cpo As XDocument = XDocument.Load(fichier)
            Dim poCue As XElement = cpo.Root.<Sequ>.FirstOrDefault
            Dim listCue As IEnumerable(Of XElement) = poCue.Elements()
     
            For Each itemCue In listCue
                If itemCue.HasElements Then
                    Dim cue As String = itemCue.<Number>.@<number>
                    strgBuilt.Append("Cue : " & cue)
                    strgBuilt.AppendLine()
     
                    Dim up As String = itemCue.<CuePart>.@<basic_fade>
                    strgBuilt.Append("up : " & up)
                    strgBuilt.AppendLine()
     
                    Dim txt As String = itemCue.<CuePart>.@<name>
                    If Not txt = String.Empty Then
                        strgBuilt.Append("TEXT : " & txt)
                        strgBuilt.AppendLine()
                    Else : txt = itemCue.<InfoItems>.<Info>.Value
                        If Not txt = String.Empty Then
                            strgBuilt.Append("TEXT : " & txt)
                            strgBuilt.AppendLine()
                        End If
                    End If
     
                    Dim poCueData As XElement = itemCue.<CueDatas>.FirstOrDefault
                    Dim listCueData As IEnumerable(Of XElement) = poCueData.Elements
     
                    For Each itemCueData In listCueData
                        If itemCueData.HasElements Then
     
                            Dim chan As String = itemCueData.<Channel>.@<channel_id>
                            strgBuilt.Append("chan : " & chan)
     
                            Dim valeur As String = itemCueData.<Value>.Value
                            strgBuilt.Append("   value : " & valeur)
                            strgBuilt.AppendLine()
     
                        End If
                    Next
     
                    strgBuilt.AppendLine()
                End If
            Next
     
            SaveToFile(txtFilePath)
        End Sub

  9. #9
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    59
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2003
    Messages : 59
    Points : 31
    Points
    31
    Par défaut
    Merci pour ton aide précieuse.

    Effectivement je trouve ta deuxième solution plus explicite, j'ai donc décidé de la mettre en application, mais lors de l’exécution du programme, visual studio me sort une erreur pour cette ligne :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Dim listCue As IEnumerable(Of XElement) = poCue.Elements()
    l'erreur est :
    La référence d'objet n'est pas définie à une instance d'un objet.
    j'ai essayé de mettre new devant IEnumerable mais ça ne marche pas

    Sais tu ce qui cloche ?

  10. #10
    Membre éprouvé
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    665
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 665
    Points : 1 161
    Points
    1 161
    Par défaut
    Bonjour,
    ton code XML est dans un espace de noms.
    Comme le dit MSDN, le plus simple est d'importer l'espace de noms :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    Imports System.Xml
    Imports <xmlns="http://schemas.malighting.de/grandma2/xml/MA">
    Pour connaitre ce Namespace, tu peux le récupérer avec ce bout de code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
            Dim cpo As XDocument = XDocument.Load(fichier)
            Dim aw As XNamespace = cpo.Root.GetDefaultNamespace
            MessageBox.Show(aw.NamespaceName)
    A partir de la il doit être possible de se servir de cette récupération pour écrire des requêtes (comme en C#), sans avoir à l'importer en dure.
    Mais là je sèche.

  11. #11
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    59
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2003
    Messages : 59
    Points : 31
    Points
    31
    Par défaut
    Super ça marche en rajoutant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Imports <xmlns="http://schemas.malighting.de/grandma2/xml/MA">
    j'ai adapté le code à ce que je veux faire et je trouve que c'est bien plus facile.

    Merci encore.

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

Discussions similaires

  1. Convertir un XML en XLS
    Par vanoou dans le forum XML/XSL et SOAP
    Réponses: 4
    Dernier message: 15/10/2010, 16h43
  2. programme pour convertir xml en txt
    Par kensem dans le forum C#
    Réponses: 26
    Dernier message: 08/10/2010, 13h24
  3. [XSLT] Conversion xml vers txt ou mdb etc
    Par narodar dans le forum XSL/XSLT/XPATH
    Réponses: 1
    Dernier message: 23/06/2006, 14h31
  4. Réponses: 5
    Dernier message: 08/07/2005, 16h46
  5. [String]Convertir pour xml
    Par Pill_S dans le forum Format d'échange (XML, JSON...)
    Réponses: 2
    Dernier message: 05/11/2004, 19h41

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