Maison > développement back-end > Golang > le corps du texte

Comment récupérer tous les éléments d'un tableau XML dans Golang sans se limiter au premier élément ?

DDD
Libérer: 2024-10-24 06:02:30
original
728 Les gens l'ont consulté

How to Retrieve All Elements in an XML Array in Golang without Limiting to Just the First Element?

Désassembler les éléments d'un tableau en XML : récupérer tous les éléments, pas seulement le premier

Lors de la désorganisation d'un tableau XML dans Golang à l'aide de xml.Unmarshal( []byte(p.Val.Inner), &t), vous pouvez rencontrer une situation dans laquelle seul le premier élément est récupéré. Pour résoudre ce problème, utilisez xml.Decoder et invoquez à plusieurs reprises sa méthode Decode.

Étapes pour désassembler tous les éléments du tableau XML :

  1. Créez un nouveau XML. Décodeur utilisant xml.NewDecoder(bytes.NewBufferString(VV)), où VV est la chaîne XML contenant les éléments du tableau.
  2. Entrez une boucle pour traiter chaque élément XML :
  3. Déclarez une variable t du type de tranche cible (par exemple, HostSystemIdentificationInfo).
  4. Appelez d.Decode(&t) pour désassembler l'élément XML suivant dans la variable t.
  5. Répétez les étapes 2 à 4 jusqu'à ce que d. L'appel Decode(&t) renvoie io.EOF.

Code Golang modifié :

<code class="go">package main

import (
    "bytes"
    "encoding/xml"
    "fmt"
    "io"
    "log"
)

type HostSystemIdentificationInfo []struct {
    IdentiferValue string `xml:"identifierValue"`
    IdentiferType  struct {
        Label   string `xml:"label"`
        Summary string `xml:"summary"`
        Key     string `xml:"key"`
    } `xml:"identifierType"`
}

func main() {
    d := xml.NewDecoder(bytes.NewBufferString(VV))
    for {
        var t HostSystemIdentificationInfo
        err := d.Decode(&t)
        if err == io.EOF {
            break
        }
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(t)
    }
}

const VV = `<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
  <identifierValue> unknown</identifierValue>
  <identifierType>
    <label>Asset Tag</label>
    <summary>Asset tag of the system</summary>
    <key>AssetTag</key>
  </identifierType>
</HostSystemIdentificationInfo>
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
  <identifierValue>Dell System</identifierValue>
  <identifierType>
    <label>OEM specific string</label>
    <summary>OEM specific string</summary>
    <key>OemSpecificString</key>
  </identifierType>
</HostSystemIdentificationInfo>
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
  <identifierValue>5[0000]</identifierValue>
  <identifierType>
    <label>OEM specific string</label>
    <summary>OEM specific string</summary>
    <key>OemSpecificString</key>
  </identifierType>
</HostSystemIdentificationInfo>
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
  <identifierValue>REDACTED</identifierValue>
  <identifierType>
    <label>Service tag</label>
    <summary>Service tag of the system</summary>
    <key>ServiceTag</key>
  </identifierType>
</HostSystemIdentificationInfo>`</code>
Copier après la connexion

Exemple de sortie :

[{ unknown {Asset Tag Asset tag of the system AssetTag}}]
[{Dell System {OEM specific string OEM specific string OemSpecificString}}]
[{5[0000] {OEM specific string OEM specific string OemSpecificString}}]
[{REDACTED {Service tag Service tag of the system ServiceTag}}]
Copier après la connexion

En utilisant xml.Decoder et en appelant Decode à plusieurs reprises, vous pouvez récupérer avec succès tous les éléments du tableau XML, résolvant ainsi le problème de l'obtention uniquement du premier élément.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!