1 回答

TA貢獻1830條經驗 獲得超9個贊
您可以使用帶有 XML 標記選項的切片,any
來告訴encoding/xml
包將任何 XML 標記放入其中。這記錄在xml.Unmarshal()
:
If the XML element contains a sub-element that hasn't matched any
? ?of the above rules and the struct has a field with tag ",any",
? ?unmarshal maps the sub-element to that struct field.
對于<ifindexXX>標簽,使用另一個包含XMLNametype 字段的結構xml.Name,因此如果您需要僅過濾以 開頭的字段,則實際字段名稱將可用ifindex。
讓我們解析以下 XML:
<root>
? ? <nic_cnt>2</nic_cnt>
? ? <ifindex1>eno1</ifindex1>
? ? <ifindex2>eno2</ifindex2>
</root>
我們可以用以下方法對其進行建模:
type Root struct {
? ? NicCnt? int? ? ?`xml:"nic_cnt"`
? ? Entries []Entry `xml:",any"`
}
type Entry struct {
? ? XMLName xml.Name
? ? Value? ?string `xml:",innerxml"`
}
解析它的示例代碼:
var root Root
if err := xml.Unmarshal([]byte(src), &root); err != nil {
? ? panic(err)
}
fmt.Printf("%+v", root)
輸出(在Go Playground上嘗試):
{NicCnt:2 Entries:[
? ? {XMLName:{Space: Local:ifindex1} Value:eno1}
? ? {XMLName:{Space: Local:ifindex2} Value:eno2}]}
請注意,Root.Entries還將包含其他未映射的 XML 標記。如果您只關心以 開頭的標簽ifindex,則可以通過以下方式“過濾”它們:
for _, e := range root.Entries {
? ? if strings.HasPrefix(e.XMLName.Local, "ifindex") {
? ? ? ? fmt.Println(e.XMLName.Local, ":", e.Value)
? ? }
}
如果 XML 還包含附加標簽:
<other>something else</other>
輸出將是(在Go Playground上嘗試這個):
{NicCnt:2 Entries:[
? ? {XMLName:{Space: Local:ifindex1} Value:eno1}
? ? {XMLName:{Space: Local:ifindex2} Value:eno2}
? ? {XMLName:{Space: Local:other} Value:something else}]}
ifindex1 : eno1
ifindex2 : eno2
- 1 回答
- 0 關注
- 144 瀏覽
添加回答
舉報