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>
}