go文件
package main import ( "fmt" "encoding/xml" "os" "text/template" ) type Member struct { Name string `xml:"name,attr"` Comment string `xml:"comment,attr"` } type Struct struct { Name string `xml:"name,attr"` Comment string `xml:"comment,attr"` Members []Member `xml:"member"` } type Result struct { XMLName xml.Name `xml:"result"` Structs []Struct `xml:"struct"` } var result = Result{} func main() { if !parse() { return } if !output() { return } fmt.Print("OK") } func parse() bool { file, err := os.Open("struct.xml") if err != nil { fmt.Print(err) return false } var buffer [1024]byte n, rerr := file.Read(buffer[0:]) if rerr != nil { fmt.Print(rerr) return false } err = xml.Unmarshal(buffer[0:n], &result) if err != nil { fmt.Print(err) return false } return true } func output() bool { file, err := os.Create("Struct.h") if err != nil { fmt.Print(err) return false } t, err := template.ParseFiles("Struct_h.tpl") if err != nil { fmt.Print(err) return false } err = t.Execute(file, result.Structs) if err != nil { fmt.Print(err) return false } return true }
xml文件
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <result> <struct name="A" comment="a结构"> <member name="A1" comment="A1注释"/> <member name="A2" comment="A2注释"/> <member name="A3" comment="A3注释"/> </struct> <struct name="B" comment="b结构"> <member name="B1" comment="B1注释"/> <member name="B2" comment="B2注释"/> <member name="B3" comment="B3注释"/> </struct> </result>
tpl文件
{{range .}} // {{.Comment}} struct {{.Name}} { {{range .Members}} // {{.Comment}} uint32_t {{.Name}}; {{end}} }; {{end}}
输出
// a结构 struct A { // A1注释 uint32_t A1; // A2注释 uint32_t A2; // A3注释 uint32_t A3; }; // b结构 struct B { // B1注释 uint32_t B1; // B2注释 uint32_t B2; // B3注释 uint32_t B3; };
有疑问加站长微信联系(非本文作者)