2022-09-28 encoding/xml包的简单使用

encoding/xml的使用

Marshal序列化/Unmarshal反序列化

1.Marshal序列化:将结构体序列化成的[]byte

type Person struct {
   XMLName xml.Name `xml:"person"`   //这个代表xml的根元素名为 person
   Name string     `xml:"name"`       //名为name的子节点
   Age int32         `xml:"age"`       //名为age的子节点
}
//marshal:将结构体编码成xml格式的[]byte
func testXmlMarsher(){
   p :=Person{
      Name: "huige",
      Age: 20,
   }
   //编码成xml无缩进
   b1 ,_ := xml.Marshal(p)
   fmt.Println("b1:=",string(b1))

   //编码成xml有缩进
   b2,_ := xml.MarshalIndent(p,"    ","    ")
   fmt.Println("b2:=",string(b2))
}

2.Unmarshal反序列化:一般用于将xml文件的数据反序列化到某个struct中

//Unmarshal:将xml形式的[]byte解码到一个结构体中
func testXmlUnmarsher(){
   b := ` <person>
         <name>huige</name>
         <age>20</age>
         </person>`
   data :=[]byte(b)
   var person Person
   xml.Unmarshal(data,&person)
   fmt.Printf("person: %v\n", person)
}
//使用ioutil快速读取xml文件data,使用Unmarshal反序列化data到struct中,
func ReadXmlFile(){
   data,_:=ioutil.ReadFile("a.xml")
   var person Person
   xml.Unmarshal(data,&person)
   fmt.Println("person:=",person)
}

Decode编码/Encode解码

写xml文件。

func WriteXml(){
   p :=Person{
      Name: "huige",
      Age: 20,
   }
   fd,_:=os.OpenFile("my.xml",os.O_CREATE|os.O_RDWR,0777)
   encoder := xml.NewEncoder(fd) //创建一个encoder
   encoder.Encode(p)            //将结体数据以xml形式保存到文件中
}

读取层级比较多的xml的栗子

假如我们有一个如下xml:

<Config>
    <account>root</account>
    <password>root</password>
    <mysql>game</mysql>
    <address>127.0.0.1</address>
    <cmd>
        <data>
            <seq>0</seq>
            <creator>test</creator>
            <type>2</type>
            <cmdstr>CmdToForbidRegisterRole 0</cmdstr>
        </data>
    </cmd>
</Config>

我们应该如何定义结构体呢?正确应该是一个一个父标签一个结构体。
根据上面xml我们定义结构体如下:

type Route struct {
    Cmdlist []Cmd `xml:"data"`
}

type Cmd struct {
    Index   int32  `xml:"seq"`
    Type    int32  `xml:"type"`
    Creator string `xml:"creator"`
    CmdStr  string `xml:"cmdstr"`
}
type Command struct {
    XMLName  xml.Name `xml:"Config"`
    Account  string   `xml:"account"`
    Password string   `xml:"password"`
    DBName   string   `xml:"mysql"`
    Address  string   `xml:"address"`
    CmdRoute Route    `xml:"cmd"`
}

第一层父标签Config我们对应Command结构体,第二层父标签cmd我们定义Route结构体,第三个层ata父标签我们定义Cmd结构体。这样我们只要层层嵌套,就能把xml反序列化到Comand对象中。
注意
1.xml根节点需要使用XMLName xml.Name xml:"Config"指明
2.结构体字段需要大写,否则反序列化报错。
3.如果是整数请确定使用int32或者int64,不要使用int.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容