>  기사  >  백엔드 개발  >  Golang에서 언마샬링하는 동안 XML 배열의 모든 요소를 ​​캡처하는 방법은 무엇입니까?

Golang에서 언마샬링하는 동안 XML 배열의 모든 요소를 ​​캡처하는 방법은 무엇입니까?

Patricia Arquette
Patricia Arquette원래의
2024-10-24 06:16:02900검색

How to Capture All Elements in an XML Array During Unmarshaling in Golang?

XML 배열을 언마샬링하여 Golang의 모든 요소 캡처

문제:

XML 배열을 구조체로 언마샬링할 때, 배열의 첫 번째 요소만 검색됩니다.

원래 코드:

<code class="go">type HostSystemIdentificationInfo []struct {
    IdentiferValue string `xml:"identifierValue"`
    IdentiferType  struct {
        Label   string `xml:"label"`
        Summary string `xml:"summary"`
        Key     string `xml:"key"`
    } `xml:"identifierType"`
}

func unmarshal(xmlBytes []byte) (HostSystemIdentificationInfo, error) {
    var t HostSystemIdentificationInfo
    err := xml.Unmarshal(xmlBytes, &t)
    return t, err
}</code>

문제:

위 코드는 XML 문자열을 HostSystemIdentificationInfo 구조체 조각으로 역마샬링하려고 시도하지만 배열의 첫 번째 요소만 캡처합니다.

해결책:

XML 배열을 사용하려면 XML 디코더를 사용하고 해당 Decode 메서드를 여러 번 호출해야 합니다. 아래 코드는 이를 달성하는 방법을 보여줍니다.

<code class="go">// ... (same struct definitions as in the original code)

func unmarshal(xmlBytes []byte) (HostSystemIdentificationInfo, error) {
    dec := xml.NewDecoder(bytes.NewReader(xmlBytes))
    var t HostSystemIdentificationInfo
    for {
        err := dec.Decode(&t)
        if err == io.EOF {
            break
        }
        if err != nil {
            return nil, err
        }
    }
    return t, nil
}</code>

설명:

  • xml.NewDecoder 함수는 io에서 읽는 새로운 XML 디코더를 생성합니다. .Reader.
  • for 루프는 XML 입력을 반복하여 각 요소를 t 슬라이스로 디코딩합니다.
  • dec.Decode(&t) 메서드는 다음 XML 요소를 변수 t로 디코딩합니다.
  • 파일 끝(EOF)에 도달할 때까지 루프가 계속되어 모든 요소가 처리되었음을 나타냅니다.

사용법:

<code class="go">xmlBytes = []byte(`
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
  <identifierValue>...</identifierValue>
  <identifierType>...</identifierType>
</HostSystemIdentificationInfo>
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
  <identifierValue>...</identifierValue>
  <identifierType>...</identifierType>
</HostSystemIdentificationInfo>
`)

t, err := unmarshal(xmlBytes)
if err != nil {
    log.Fatal(err)
}

fmt.Println(t) // All elements of the XML array will be printed</code>

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

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