C
C
cascado2017-04-26 15:28:48
go
cascado, 2017-04-26 15:28:48

How to parse an XML element with arbitrary attributes when using encoding/xml?

Good afternoon. It is required to parse such an element XML element . I do not know in advance all the options for attributes, I would like to collect them somehow in a bunch, for example, in a dictionary. Now something like this is the code , but it only implements the extraction of values ​​from all nodes, but not attributes. Is this possible, maybe there are some custom packages for these actions, maybe someone has an example of implementation through interface {}, give me some ideas. Thank you in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor, 2017-10-19
@cascado

type Rewards struct {
  XMLName xml.Name `xml:"rewards"`
  Rewards []Reward `xml:"reward"`
}

type Reward struct {
  Value string
  Attrs map[string]string
}

func (r *Reward) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
  r.Attrs = make(map[string]string)
  for _, attr := range start.Attr {
    r.Attrs[attr.Name.Local] = attr.Value
  }
  if err := d.DecodeElement(&r.Value, &start); err != nil {
    return err
  }
  return nil
}
// ...
var obj Rewards
if err := xml.Unmarshal(data, &obj); err != nil {
  log.Fatal(err)
}
log.Printf("%+v", obj.Rewards)

[{Value:100 Attrs:map[type:money slot:101 repeated:1]} {Value:1 Attrs:map[bagId:1 repeated:1 type:freedomBagsExp]} {Value:30 Attrs:map[repeated:1 type:rating]} {Value:1 Attrs:map[repeated:1 type:key key_id:2]} {Value:30 Attrs:map[type:guildAP repeated:1]} {Value:2 Attrs:map[key_id:2 repeated:1 type:key]} {Value:476 Attrs:map[repeated:1 type:rating]}]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question