GoでXMLアンマーシャリング中にすべての配列要素を取得するにはどうすればよいですか?

DDD
リリース: 2024-10-24 00:16:01
オリジナル
452 人が閲覧しました

How to Retrieve All Array Elements During XML Unmarshaling in Go?

Go での XML 配列のアンマーシャリング: すべての要素のキャプチャ

提供されたコードでは、複数のインスタンスを含む XML 文字列をアンマーシャリングするときに問題が発生します。特定の構造体の型。現在の実装では、配列の最初の要素のみを取得します。

この制限を克服するには、次のアプローチを検討してください。

XML デコーダーの使用

xml.Decoder を使用すると、XML データを反復処理して、構造体のすべてのインスタンスを取得できます。更新されたコードは次のとおりです:

<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>
ログイン後にコピー

囲碁で遊ぶ:

[Playground Link](http://play.golang.org/p/c7-E_Afe) -3)

以上がGoでXMLアンマーシャリング中にすべての配列要素を取得するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!