You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
goxml/goxml.go

44 lines
998 B

2 years ago
package goxml
import (
"encoding/xml"
"io"
"strings"
)
func XmlDecode(data string) map[string]string {
decoder := xml.NewDecoder(strings.NewReader(data))
result := make(map[string]string)
key := ""
for {
token, err := decoder.Token() //读取一个标签或者文本内容
if err == io.EOF {
return result
}
if err != nil {
return result
}
switch tp := token.(type) { //读取的TOKEN可以是以下三种类型StartElement起始标签EndElement结束标签CharData文本内容
case xml.StartElement:
2 years ago
se := tp //强制类型转换
2 years ago
if se.Name.Local != "xml" {
key = se.Name.Local
}
if len(se.Attr) != 0 {
//读取标签属性
}
case xml.EndElement:
2 years ago
ee := tp
2 years ago
if ee.Name.Local == "xml" {
return result
}
case xml.CharData: //文本数据,注意一个结束标签和另一个起始标签之间可能有空格
2 years ago
cd := tp
2 years ago
data := strings.TrimSpace(string(cd))
if len(data) != 0 {
result[key] = data
}
}
}
}