亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang xml.Unmarshall 任意元素

Golang xml.Unmarshall 任意元素

Go
嚕嚕噠 2023-06-05 09:13:34
具有任意數量的任意命名元素的 XML:<modules><elt1><version>1.2.3</version></elt1><eltN><version>4.5.6</version></eltN></modules>如何將其解析為map[string]stringfor elementnameto version?我發現的所有 Unmarshall 示例都采用靜態元素名稱。
查看完整描述

1 回答

?
SMILET

TA貢獻1796條經驗 獲得超4個贊

您可以改用xml.Decoder:?Example, 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 ""

}


查看完整回答
反對 回復 2023-06-05
  • 1 回答
  • 0 關注
  • 216 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號