0

I'm having trouble parsing xml in Go. Can anyone help? The XML format is:

<Feed version='1.03' format='FULL' date='2016-04-22T18:31:01.4988282+01:00'>

    <Ids>
            <Id code='000001' quantity='4' />
            <Id code='000002' quantity='0' />
     </Ids>

</Feed>
2
  • What do you want to parse out of it? What have you tried? Where did you get stuck? Check out the encoding/xml package to get started. Commented Apr 24, 2016 at 16:35
  • ive just managed to work it out. i was missing the "attr" to pick up the attributes of the Id. Commented Apr 24, 2016 at 16:47

1 Answer 1

1

For anyone wondering, here's a sample that will roundtrip the mentioned XML to go structs and back:

func TestXml(t *testing.T) {
    type Id struct {
        Code string `xml:"code,attr"`
        Quantity int `xml:"quantity,attr"`
    }

    type Feed struct {
        Version string `xml:"version,attr"`
        Format string `xml:"format,attr"`
        Date string `xml:"date,attr"`
        Ids []Id `xml:"Ids>Id"`
    }

    x := []byte(`
        <Feed version='1.03' format='FULL' date='2016-04-22T18:31:01.4988282+01:00'>
            <Ids>
                <Id code='000001' quantity='4' />
                <Id code='000002' quantity='0' />
            </Ids>
        </Feed>
    `)

    f := Feed{}
    xml.Unmarshal(x, &f)
    t.Logf("%#v", f)
    t.Log("Code 0:", f.Ids[0].Code)

    b, _ := xml.Marshal(f)
    t.Log(string(b))
}

This produces the following output:

xml_test.go:42: domain.Feed{Version:"1.03", Format:"FULL", Date:"2016-04-22T18:31:01.4988282+01:00", Ids:[]domain.Id{domain.Id{Code:"000001", Quantity:4}, domain.Id{Code:"000002", Quantity:0}}}
xml_test.go:43: Code 0: 000001
xml_test.go:46: <Feed version="1.03" format="FULL" date="2016-04-22T18:31:01.4988282+01:00"><Ids><Id code="000001" quantity="4"></Id><Id code="000002" quantity="0"></Id></Ids></Feed>

The documentation for xml contains great examples.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.