Go语言 如何解组嵌套XML?

odopli94  于 2023-01-06  发布在  Go
关注(0)|答案(1)|浏览(150)

我有以下XML文件(config-test.xml)要解组:

<configuration version="37">
  <folder id="0usj3" label="aaa" type="sendreceive">
    <device id="U34L32N"></device>
    <device id="U34L32NXX"></device>
    <device id="U34L32NYY"></device>
  </folder>
  <folder id="0usj4" label="bbb" type="sendreceive">
    <device id="U34L32NYY"></device>
  </folder>
  <device id="U34L32N" name="wazaa"></device>
  <device id="FJP7437" name="wazii"></device>
</configuration>

这是我使用的代码:

package main

import (
    "encoding/xml"
    "fmt"
    "io"
    "os"

    "github.com/rs/zerolog/log"
)

type Device struct {
    ID   string `xml:"id,attr"`
    Name string `xml:"name,attr"`
}

type Folder struct {
    ID     string `xml:"id,attr"`
    Label  string `xml:"label,attr"`
    Type   string `xml:"type,attr"`
    Device []Device
}

type Configuration struct {
    Folder []Folder `xml:"folder"`
    Device []Device `xml:"device"`
}

func main() {
    var err error

    xmlFile, errOpen := os.Open("config-test.xml")
    byteValue, errRead := io.ReadAll(xmlFile)
    if errOpen != nil || errRead != nil {
        log.Fatal().Msgf("cannot open (%v) or read (%v) config.xml: %v", errOpen, errRead)
    }
    defer xmlFile.Close()

    config := Configuration{}
    err = xml.Unmarshal(byteValue, &config)
    if err != nil {
        log.Fatal().Msgf("cannot unmarshall XML: %v", err)
    }

    fmt.Printf("%v", config)
}

我得到一个部分结果:

{[{0usj3 aaa sendreceive []} {0usj4 bbb sendreceive []}] [{U34L32N wazaa} {FJP7437 wazii}]}

它是部分的,因为XML被正确解析,但是嵌套在<folder>中的<device>条目没有被考虑。
有没有特殊的方法来标记这些嵌套的元素?

wpx232ag

wpx232ag1#

Folder中的Device上缺少注解。

type Folder struct {
    ID     string   `xml:"id,attr"`
    Label  string   `xml:"label,attr"`
    Type   string   `xml:"type,attr"`
    Device []Device `xml:"device"`
}

相关问题