>  기사  >  백엔드 개발  >  Go에서 XML 언마샬링 중 모든 배열 요소를 검색하는 방법은 무엇입니까?

Go에서 XML 언마샬링 중 모든 배열 요소를 검색하는 방법은 무엇입니까?

DDD
DDD원래의
2024-10-24 00:16:01453검색

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>

Go로 플레이하기:

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

위 내용은 Go에서 XML 언마샬링 중 모든 배열 요소를 검색하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.