The question is more of a 'can go do this?' then solving a real problem.
package main
import (
"encoding/xml"
"fmt"
"log"
)
type Example struct {
Float Float
Float3 Float `printf:"%.3f"`
Float7 Float `printf:"%.7f"`
}
type Float float64
func main() {
e := Example{
Float: 1.0,
Float3: 2.0,
Float7: 3.0,
}
b, err := xml.MarshalIndent(e, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(b))
}
https://play.golang.org/p/Dq9M9UvwS4Q
Above example outputs:
<Example>
<Float>1</Float>
<Float3>2</Float3>
<Float7>3</Float7>
</Example>
But I would like it to be:
<Example>
<Float>1</Float>
<Float3>2.000</Float3>
<Float7>3.0000000</Float7>
</Example>
So I would like to use the struct tags to influence the xml output format of those fields. I don't think I believe I can use the MarshalXML
method on the Float
type because I don't have access to the struct tag at that point. I can create a MarshalXML
for the Example type but that would mean copying a lot of the marshalling logic from encoding/xml/marshal.go
. Is there a way to use struct tags when marshalling a specific field?
How can I use struct tags when marshalling xml fields?
You cannot do this. Package encoding/xml does not support what you are asking for.
Is there a way to use struct tags when marshalling a specific field?
No. And for good reason. Marshaling and unmarshaling is a 1-to-1 conversion. If it's possible to do arbitrary formatting, you lose that guarantee.
If you have need for a data type that acts like a float with three decimals of precision, you should make this a distinct data type, not rely on arbitrary, lossy formatting of a generic float type.
Now, of course, you could write your own library to honor arbitrary struct tags, and you could get this functionality. While this might make sense in some contexts, for marshaling of XML (or any other defined data transfer format), I strongly discourage this for the reasons described above.