如果要解析的文档像这样:
<ap> //或者 <ap name="哈哈" age="28">
<head>
<tr_code>420102</tr_code>
<corp_no>8000086484</corp_no>
</head>
<body>
<IdNb>1314714361242975</IdNb>
<Tp>AC01</Tp>
</body>
</ap>
你就可以这样来解析:
package main
import (
"encoding/xml" //这个是解析xml的包
"fmt"
)
type Student struct {
XMLName xml.Name `xml:"ap"`
Name string `xml:"name,attr"` //如果标签里面有 <ap name="哈哈" age="28"> 就可以这样写否则忽略Name字段
Age int `xml:"age,attr"` //如果标签里面有 <ap name="哈哈" age="28"> 就可以这样写否则忽略Age字段
Tr_code []string `xml:"head>tr_code",` //head 标签下的子标签 tr_code 字段
Corp_no []string `xml:"head>corp_no",`
IdNb []string `xml:"body>IdNb",` //body 标签下的子标签 ldNb 字段
Tp []string `xml:"body>Tp",`
}
func main() {
str := `<?xml version="1.0" encoding="utf-8"?> //这里面就是要解析的文档
<ap name="哈哈" age="28">
<head>
<tr_code>420102</tr_code>
<corp_no>8000086484</corp_no>
</head>
<body>
<IdNb>1314714361242975</IdNb>
<Tp>AC01</Tp>
</body>
</ap>`
var s Student
xml.Unmarshal([]byte(str), &s)
fmt.Println(s)
fmt.Println(s.Tr_code[0]) //420102
fmt.Println(s.Corp_no[0]) //8000086484
fmt.Println(s.IdNb[0]) //1314714361242975
fmt.Println(s.Tp[0]) //AC01
}