在Go中解封带编号的XML标记

z2acfund  于 2023-06-19  发布在  Go
关注(0)|答案(1)|浏览(148)

我已经尝试了很多结构体来尝试解组这个XML,但我真的不能弄清楚:

package main

import (
    "bytes"
    "encoding/xml"
    "fmt"
)

type SettingContainer struct {
    XMLName  xml.Name  `xml:"Settings"`
    Settings []Setting `xml:",any"`
}

type Setting struct {
    XMLName          xml.Name          `xml:",any"`
    SettingRegisters []SettingRegister `xml:",any"`
}

type SettingRegister struct {
    XMLName xml.Name `xml:",any"`
    Value   string   `xml:"value,attr"`
}

func main() {
    var xmlData = bytes.NewBufferString(`
    <Settings>
        <Setting0>
            <Setting0_register value="0x20" />
            <Setting0ArbitraryName value="0x0" />
        </Setting0>
        <Setting1>
            <Setting1_register value="0x60" />
            <Setting1WhateverEnable value="0x0" />
        </Setting1>
        <Setting2>
            <Setting2_register value="0x80" />
            <Setting2blahblah value="0x1" />
        </Setting2>
        <Setting4>
            <Setting4_register value="0x2fffff8" />
            <Setting4ThisCanBeAnything value="0x0" />
        </Setting4>
    </Settings>`)

    var s []SettingContainer
    xml.Unmarshal(xmlData.Bytes(), &s)

    for _, i := range s {
        fmt.Println(i)
    }
}

我就是打印不出来。我实际需要的字段是SettingN_register的值attr以及SettingN标记名称。我怎样才能使xml被正确地解组到这些字段中呢?我正在寻找一个定制的unmarshal函数,但我真的找不到如何正确地制作一个。我能从这个XML中得到的只是“Settings”标记名。

ryevplcw

ryevplcw1#

XMLName字段中删除xml:",any"标记(这会导致解码器尝试将额外的子元素Map到此字段),并解组为SettingContainer而不是[]SettingContainer,因为XML文档只能有一个根元素。示例如下:https://go.dev/play/p/dItnmEGH8oM

type SettingContainer struct {
    XMLName  xml.Name  `xml:"Settings"`
    Settings []Setting `xml:",any"`
}

type Setting struct {
    XMLName          xml.Name
    SettingRegisters []SettingRegister `xml:",any"`
}

type SettingRegister struct {
    XMLName xml.Name
    Value   string `xml:"value,attr"`
}

func main() {
    var xmlData = bytes.NewBufferString(`...`)

    var s SettingContainer
    xml.Unmarshal(xmlData.Bytes(), &s)

    fmt.Println(s)
}

相关问题