1. 项目地址:
    https://github.com/beevik/etree

  2. 用法:

    1. 生成:
       package main
       import (
           "fmt"
           "github.com/beevik/etree"
       )
       func main() {
           doc := etree.NewDocument()
           doc.CreateProcInst("xml", `version="1.0" encoding="UTF-8"`)
           doc.CreateProcInst("xml-stylesheet", `type="text/xsl" href="style.xsl"`)
           people := doc.CreateElement("People")
           people.CreateComment("These are all known people")
           jon := people.CreateElement("Person")
           jon.CreateAttr("name", "Jon")
           sally := people.CreateElement("Person")
           sally.CreateAttr("name", "Sally")
           doc.Indent(2)
           output,_ := doc.WriteToString()
           fmt.Println(output)
       }
       // 输出
       <?xml version="1.0" encoding="UTF-8"?>
       <?xml-stylesheet type="text/xsl" href="style.xsl"?>
       <People>
         <!--These are all known people-->
         <Person name="Jon"/>
         <Person name="Sally"/>
       </People>
    2. 解析:
       package main
       import (
           "fmt"
           "github.com/beevik/etree"
       )
       func main() {
           xml := `
       <?xml version="1.0" encoding="UTF-8"?>
       <?xml-stylesheet type="text/xsl" href="style.xsl"?>
       <People>
         <!--These are all known people-->
         <Person name="Jon"/>
         <Person name="Sally"/>
       </People>
       `
           doc := etree.NewDocument()
           if err := doc.ReadFromString(xml); err != nil {
               fmt.Println("解析出错:",err)
           }
           root := doc.SelectElement("People")
           fmt.Println("根元素名:", root.Tag)
           for _, ele := range root.SelectElements("Person") {
               fmt.Println("子元素:", ele.Tag)
               for _, attr := range ele.Attr {
                   fmt.Println(attr.Key, attr.Value)
               }
           }
       }
       // 输出
       根元素名: People
       子元素: Person
       name Jon
       子元素: Person
       name Sally
文档更新时间: 2024-04-20 10:57   作者:lee