您的位置 首页 golang

Golang操作XML神器etree

golang如何解析xml数据?相信大家的第一反应就是使用标准包encoding/xml,但是这往往需要我们提前定义好一个结构体,然后通过xml.Unmarshal将数据写入到对应的结构体。一旦xml定义起来将非常难受,今天小编给大家推荐一个超好用的xml的第三方类库可直接从xml字符串或者xml文件中读取相应的节点。

一、安装(go module)

 go get github.com/beevik/etree  

版本:

  • v1.1.0 – Feb 2, 2019
  • v1.0.1 – May 6, 2018
  • v1.0.0 – Aug 9, 2017

二、特性

  • 将XML文档表示为元素树,以便于遍历。
  • 从顶级节点开始,导入,序列化,修改或创建XML文档。
  • 向文件,字节切片,字符串和io接口读写XML。
  • 使用类似XPath的轻量级查询API方式,执行简单或复杂的搜索
  • 使用空格或制表符自动缩进XML,以提高可读性。
  • 建立在go标准包encoding / xml基础之上

三、基本使用

1.写入xml文件

 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"`)
	// 设置节点
	students := doc.CreateElement("Students")

	tom := students.CreateElement("Student")
	tom.CreateAttr("name", "tom")
	tom.CreateAttr("age", "20")
	tom.CreateAttr("gender", "male")

	lucy := students.CreateElement("Student")
	lucy.CreateAttr("name", "lucy")
	lucy.CreateAttr("age", "18")
	lucy.CreateAttr("gender", "female")

	// 设置缩进
	doc.Indent(4)
	
	if err := doc.WriteToFile("./students.xml"); err != nil {
		fmt.Println("写入失败, reason:" + err.Error())
	}

}  

2.从文件读取

我就直接读取刚刚生成的studnet.xml

 	doc := etree.NewDocument()
	if err := doc.ReadFromFile("./students.xml"); err != nil {
		fmt.Println("读取失败, reason:" + err.Error())
	}

	// 读取Students下面的所有子节点
	students := doc.SelectElement("Students").ChildElements()
	if len(students) > 0 {
		for _, v := range  students {
      // 获取xml中节点的name属性值
			name := v.SelectAttr("name").Value
			age := v.SelectAttr("age").Value
			gender := v.SelectAttr("gender").Value
			fmt.Printf("%s: 性别为:%s, 年龄为: %s \n", name, gender, age)
		}
	}  

etree的功能非常强大,我们还可以通过RemoveAttr、RemoveChild等移除节点,节点属性。感兴趣的同学可以去pkg.go.dev查看官方的文档

文章来源:智云一二三科技

文章标题:Golang操作XML神器etree

文章地址:https://www.zhihuclub.com/98608.shtml

关于作者: 智云科技

热门文章

评论已关闭

12条评论

  1. Also, all members of the household, except pregnant women, should be given the antibiotic rifampin to prevent infection.

  2. He likes to do long term business and plans to fda approved male enhancement pills charge mobile viagra pills for sexually active phone manufacturers for technology royalties in the future

  3. Mastectomy has been the standard surgical offer for MBC whereas breast conserving therapy is widely used for selected females with the disease and has been shown to be effective in the long term 6, 7, 8

  4. All the drugs that are associated with Adrenal insufficiency flagyl ramipril ratiopharm 2 5 mg compresse May 27 Then US congressman Weiner sends a waist down photo to a 21 year old female college student in Seattle

  5. CVS carries them where it s legal Twelve of 17 patients completed the core period of the trial in which 2

  6. As described herein, the invention employs methods for clustering genes into gene expression profiles by determining their expression levels in two different cell or tissue samples

  7. Continuous prophylactics may be considered in those with attacks refractory to short term therapies BeneЕЎovГЎ M, TrejbalovГЎ K, KovГЎЕ™ovГЎ D, VernerovГЎ Z, Hron T, KuДЌerovГЎ D, Hejnar J

网站地图