Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encoding/xml: cannot get array, only get the first element #22657

Closed
anotherGoogleFan opened this issue Nov 10, 2017 · 1 comment
Closed

encoding/xml: cannot get array, only get the first element #22657

anotherGoogleFan opened this issue Nov 10, 2017 · 1 comment

Comments

@anotherGoogleFan
Copy link

anotherGoogleFan commented Nov 10, 2017

Please answer these questions before submitting your issue. Thanks!

What version of Go are you using (go version)?

go version go1.9.2 windows/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

set GOARCH=amd64
set GOBIN=
set GOEXE=.exe
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOOS=windows
set GOPATH=E:\GoProject
set GORACE=
set GOROOT=C:\Go
set GOTOOLDIR=C:\Go\pkg\tool\windows_amd64
set GCCGO=gccgo
set CC=gcc
set GOGCCFLAGS=-m64 -mthreads -fmessage-length=0
set CXX=g++
set CGO_ENABLED=1
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config

What did you do?

package main

import (
	"encoding/xml"
	"fmt"
)

type server struct {
	ServerName string `xml:"serverName"`
	ServerIP   string `xml:"serverIP"`
}

func main() {
	data := []byte(`
    <server>
        <serverName>Shanghai_VPN</serverName>
        <serverIP>127.0.0.1</serverIP>
    </server>
    <server>
        <serverName>Beijing_VPN</serverName>
        <serverIP>127.0.0.2</serverIP>
    </server>
`)
	var v []server
	err := xml.Unmarshal(data, &v)
	if err != nil {
		fmt.Printf("error: %v", err)
		return
	}

	fmt.Println(v)
}

What did you expect to see?

[{Shanghai_VPN 127.0.0.1} {Beijing_VPN 127.0.0.2}]

What did you see instead?

[{Shanghai_VPN 127.0.0.1}]

@mvdan
Copy link
Member

mvdan commented Nov 10, 2017

See the Unmarshal docs:

UnmarshalXML decodes a single XML element beginning with the given start element.

You may decode multiple top-level elements by calling decode multiple times, as seen in https://stackoverflow.com/questions/27553274/unmarshal-xml-array-in-golang-only-getting-the-first-element.

Otherwise, instead of using <elem></elem><elem></elem>, you could use <elems><elem></elem><elem></elem></elems> to have a single top-level element.

@mvdan mvdan closed this as completed Nov 10, 2017
@golang golang locked and limited conversation to collaborators Nov 10, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants