Go语言 解组任意元素

2nc8po8w  于 2022-12-07  发布在  Go
关注(0)|答案(1)|浏览(209)

具有任意数量的任意命名元素的XML:

<modules>
<elt1><version>1.2.3</version></elt1>
<eltN><version>4.5.6</version></eltN>
</modules>

如何将它解析为map[string]string,以便将elementname解析为version?我找到的所有解编集示例都假定为静态元素名称。

2uluyalo

2uluyalo1#

您可以改用xml.DecoderExample, which severely lacks error handling

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 ""
}

相关问题