两个核心函数Marshal Unmarshal
结构体转xml
func test1() {
type Address struct {
City, State string
}
type Person struct {
XMLName xml.Name `xml:"person"`
Id int `xml:"id,attr"`
FirstName string `xml:"name>first"`
LastName string `xml:"name>last"`
Age int `xml:"age"`
Height float32 `xml:"height,omitempty"`
Married bool
Address
Comment string `xml:",comment"`
}
v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42, Height: 1.82}
v.Comment = " Need more details. "
v.Address = Address{"Hanga Roa", "Easter Island"}
// 后面两个参数 缩进格式
// output, err := xml.Marshal(v)
output, err := xml.MarshalIndent(v, " ", " ")
if err != nil {
fmt.Printf("error: %v\n", err)
}
os.Stdout.Write(output)
}
运行结果如下:(第一个运行结果为没有缩进格式,第二个是设置了缩进格式)
读取xml文件
func test2() {
type Email struct {
Where string `xml:where,attr`
Addr string
}
type Address struct {
City, State string
}
type Result struct {
XMLName xml.Name `xml:"person"`
Id int `xml:"id,attr"`
FirstName string `xml:"name>first"`
LastName string `xml:"name>last"`
Age int `xml:"age"`
Height float32 `xml:"height,omitempty"`
Married bool
Email []Email
Groups []string `xml:"Group>Value"`
Address
Comment string `xml:",comment"`
}
b, _ := ioutil.ReadFile("a.xml")
var v Result
xml.Unmarshal([]byte(b), &v)
fmt.Printf("p: %v\n", v)
fmt.Printf("XMLName: %#v\n", v.XMLName)
fmt.Printf("Id: %v\n", v.Id)
fmt.Printf("Name: %v\n", v.FirstName)
fmt.Printf("Phone: %v\n", v.LastName)
fmt.Printf("Age: %v\n", v.Age)
fmt.Printf("Height: %v\n", v.Height)
fmt.Printf("Married: %v\n", v.Married)
fmt.Printf("Email: %v\n", v.Email)
fmt.Printf("Groups: %v\n", v.Groups)
fmt.Printf("Address: %v\n", v.Address)
fmt.Printf("Comment: %v\n", v.Comment)
}
xml文件如下a.xml
<person id="13">
<name>
<first>John</first>
<last>Doe</last>
</name>
<age>42</age>
<height>1.82</height>
<Married>false</Married>
<City>Hanga Roa</City>
<State>Easter Island</State>
<Email where="home">
<Addr>gre@example.com</Addr>
</Email>
<Email where='work'>
<Addr>gre@work.com</Addr>
</Email>
<Group>
<Value>Friends</Value>
<Value>Squash</Value>
</Group>
<!-- Need more details. -->
</person>
写xml文件
func test3() {
type Person struct {
XMLName xml.Name `xml:"person"`
Name string `xml:name`
Age int `xml:age`
Email string `xml:emaik`
}
p := Person{
Name: "wang fan",
Age: 26,
Email: "1356316925@qq.com",
}
f, _ := os.OpenFile("a1.xml", os.O_RDWR|os.O_CREATE, 0777)
defer f.Close()
e := xml.NewEncoder(f)
e.Encode(p)
}
a1.xml
<person><Name>wang fan</Name><Age>26</Age><Email>1356316925@qq.com</Email></person>