XML : Restructuring xml by using only one struct type for marshal/unmarshal-ing in go

Say I have following block of xml data.

    <Result>        <person>            <name>Dave</name>        </person>        <id>            <number>1234</number>        </id>    </Result>    

and I want to restructure it to following.

    <Restructured>        <Person>Dave</Person>        <Id>1234</Id>    </Restructured>    

But only using one struct to do it. Is it possible?

Attaching code below.

  package main    import (      "encoding/xml"      "fmt"      "os"  )    type Result struct {      Person string `xml:"person>name"`      Id     int    `xml:"id>number"`  }    type Restructured struct {      Person string      Id     int  }    const data = `  <Result>      <person>          <name>Dave</name>      </person>      <id>          <number>1234</number>      </id>  </Result>`    func main() {      v := Result{}      err := xml.Unmarshal([]byte(data), &v)      if err != nil {          fmt.Printf("error: %v", err)          return      }        newV := Restructured{Person: v.Person, Id: v.Id}        output, err := xml.MarshalIndent(newV, "  ", "    ")      if err != nil {          fmt.Printf("error: %v\n", err)      }        os.Stdout.Write(output)  }    

I don't want to do it like this, allocating a new type of struct("newV") and copying field by field. Is there any way to marshal automatically with different xml tags using original struct "v"?

No comments:

Post a Comment