I have this xml api construct I need to use (this construct is not defined by me and I cannot change it):
<path><farmer id="ME7"/></path>
In go I have:
type Path struct {
XMLName xml.Name `xml:"path"`
FarmerId string `xml:"farmer id,attr"`
}
pMux := &Path{FarmerId: "ME7"}
However go encodes pMux and prints it as this:
<path xmlns:farmer="farmer" farmer:id="ME7" </path>
What I want is this:
<path><farmer id="ME7"/> </path>
How can I achieve this?
Thx
The XML is invalid, but if you really need it to come out like that, use a regular expression to fix it afterward. Here is an example.
I am assuming that you really want the open tag valid like so <path farmer id="ME7"></path>
, instead of not having the open tag valid as you posted <path farmer id="ME7" </path>
, but either way is doable with regex.
BTW, your question is inconsistent about what you want. You start with wanting <path><farmer id="ME7"></path>
, which @eugenioy 's answer will accommodate. Then end with "What I want is this: <path farmer id="ME7" </path>
". Which my answer is geared toward.
https://play.golang.org/p/A-sJhIgFZW
package main
import (
"encoding/xml"
"fmt"
"regexp"
)
type Path struct {
XMLName xml.Name `xml:"path"`
Farmer string `xml:"farmer,attr"`
FarmerId string `xml:"id,attr"`
}
func main() {
path := &Path{
FarmerId: "ME7",
}
data, err := xml.Marshal(path)
if err != nil {
fmt.Println(err)
return
}
strData := string(data)
// fix with regex
reg := regexp.MustCompile(`(farmer)(="")`)
strData = reg.ReplaceAllString(strData, "$1")
fmt.Println(strData) // <path farmer id="ME7"></path>
}
That's not valid XML.
I would double check the API contract you mention since it's unlikely they require invalid XML.
The closest you can get to that is this valid XML.
<path><farmer id="ME7"></farmer></path>
In order to generate the above (valid) XML, you should define your types as:
type Farmer struct {
XMLName xml.Name `xml:"farmer"`
Id string `xml:"id,attr"`
}
type Path struct {
XMLName xml.Name `xml:"path"`
Farmer Farmer `xml:"farmer"`
}
And then create the value as:
v := Path{Farmer: Farmer{Id: "ME7"}}
See here for a running example: https://play.golang.org/p/abEqMc6HdK