A
A
Alexander2018-06-18 15:35:46
go
Alexander, 2018-06-18 15:35:46

How to parse XML in Go?

Gentlemen, I'm trying to learn how to parse XML in Go. It seems that I understood the idea with structures and Unmarshal, but "the stone flower does not come out." There is a very simple XML:

<RESPONSE>
    <OBJECT basetype="status" name="status" oid="1">
      <PROPERTY name="response-type">success</PROPERTY>
      <PROPERTY name="response-type-numeric">0</PROPERTY>
      <PROPERTY name="response">0f738648db95bb1f6ca37f6b8b5aafa8</PROPERTY>
      <PROPERTY name="return-code">1</PROPERTY>
    </OBJECT>
</RESPONSE>

Can you please tell me how to write structures for it correctly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2018-06-18
@asand3r

https://play.golang.org/p/mC_B9Qzjvt5

package main

import (
  "encoding/xml"
  "fmt"
)

type Property struct {
  Name  string `xml:"name,attr"`
  Value string `xml:",chardata"`
}

type Object struct {
  Properties []Property `xml:"PROPERTY"`
  Basetype   string     `xml:"basetype,attr"`
  Name       string     `xml:"name,attr"`
  Oid        int        `xml:"oid,attr"`
}

type Response struct {
  XMLName xml.Name `xml:"RESPONSE"`
  Objects []Object `xml:"OBJECT"`
}

func main() {
  data := []byte(`<RESPONSE>
    <OBJECT basetype="status" name="status" oid="1">
      <PROPERTY name="response-type">success</PROPERTY>
      <PROPERTY name="response-type-numeric">0</PROPERTY>
      <PROPERTY name="response">0f738648db95bb1f6ca37f6b8b5aafa8</PROPERTY>
      <PROPERTY name="return-code">1</PROPERTY>
    </OBJECT>
</RESPONSE>`)

  var res Response
  err := xml.Unmarshal(data, &res)
  if err != nil {
    panic(err)
  }

  fmt.Printf("%+v\n", res)
}

N
noma, 2018-06-18
@noma

Write a structure.
Do the reverse operation - Marshal.
See what happens - I correct the structure - so you'll figure it out.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question