L
L
lemme2020-11-04 15:26:29
go
lemme, 2020-11-04 15:26:29

How can fields be handled in a struct?

Hey! Can you please tell me how to process the fields in the structure?

For example, there is an `xml` file in which some fields are crooked, for example, there are many spaces that you want to trim

<Document>
    <Price>100.00</Price>
</Document>
<Document>
    <Price>                 500.00</Price>
</Document>


There is a typical code that converts this file to json

type Feed struct {
  Products []Product `xml:"Document" json:"products""`
}

type Product struct {
  Price string `xml:"Price" json:"price"`
}

func main() {
  xmlFile, err := os.Open("feed.xml")
  defer xmlFile.Close()

  if err != nil {
    log.Fatal(err)
  }

  byteValue, _ := ioutil.ReadAll(xmlFile)

  var feed Feed

  xml.Unmarshal(byteValue, &feed)

  b, err := json.Marshal(feed)

  if err != nil {
    log.Fatal(err)
  }

  fmt.Println(string(b))
}


The result will be like this

{
  "products": [
    { "price": "100.00" },
    { "price": "       500.00" }
  ]
}


And I want to process the fields with the price (for example) and remove extra spaces from it

{
  "products": [
    { "price": "100.00" },
    { "price": "500.00" }
  ]
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Samsonov, 2020-11-04
@lemme

Implement custom UnmarshalXML

func (p *Product) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
  v := struct {
    Price string `xml:"Price"`
  }{}
  d.DecodeElement(&v, &start)
  p.Price = strings.Trim(v.Price, " ")
  return nil
}

https://play.golang.org/p/-U6lNP2CWDs

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question