具有任意数量的任意命名元素的XML:
<modules> <elt1><version>1.2.3</version></elt1> <eltN><version>4.5.6</version></eltN> </modules>
如何将它解析为map[string]string,以便将elementname解析为version?我找到的所有解编集示例都假定为静态元素名称。
map[string]string
elementname
version
2uluyalo1#
您可以改用xml.Decoder:Example, which severely lacks error handling。
xml.Decoder
package main import ( "encoding/xml" "fmt" "io" "strings" ) func main() { data := `<modules> <elt1><version>1.2.3</version></elt1> <eltN><version>4.5.6</version></eltN> </modules>` fmt.Println(parseVersions(strings.NewReader(data))) } func parseVersions(s io.Reader) map[string]string { r := make(map[string]string) decoder := xml.NewDecoder(s) for token, err := decoder.Token(); err == nil; token, err = decoder.Token() { switch v := token.(type) { case xml.StartElement: if el := v.Name.Local; strings.HasPrefix(el, "elt") { r[el] = parseVersion(decoder) } } } return r } func parseVersion(decoder *xml.Decoder) string { token, _ := decoder.Token() switch v := token.(type) { case xml.StartElement: if v.Name.Local == "version" { cd, _ := decoder.Token() return string(cd.(xml.CharData)) } } return "" }
1条答案
按热度按时间2uluyalo1#
您可以改用
xml.Decoder
:Example, which severely lacks error handling。