dongpu4141 2018-06-12 13:56
浏览 23
已采纳

找不到未编组的XML节点

I'm trying to unmarshal an XML file, but it's not finding my root node snapshot, which is keeping me from being able to unmarshal the rest of my file.

I'm calling parser.go from main.go, as well as the Validate function.

parser.go

type Parser struct {
    file     *ConfigXML
    filepath string
}

//Load the file
func (parser *Parser) Load() error {
    b, err := helpers.LoadFile(parser.filepath)

    if err != nil {
        return err
    }

    parser.file = nil
    xml.Unmarshal(b, &parser.file)

    return nil
}

func (parser *Parser) Validate() error {

    if len(parser.file.snapshot) == 0 {
        return fmt.Errorf("node snapshot does not exist")
    }

    return nil
}

While my XML file is large, I'll post a snippet:

<?xml version='1.0' encoding='UTF-8'?>
 <snapshot>
  <ENBEquipment id="233443234543" model="XYZ" version="LR_16_02_L">
   <attributes>
    <administrativeState>unlocked</administrativeState>
   </attributes>
  </ENBEquipment>
 </snapshot>

The structs I've created to unmarshal to:

type ConfigXML struct {
    snapshot []Snapshot
    FileName string
}

// Snapshot is root <snapshot>
type Snapshot struct {
    ENBEquipment []ENBEquipment
}

// ENBEquipment subtag of <snapshot> -> <ENBEquipment>
type ENBEquipment struct {
    ID              string `xml:"id,attr"`
    DeviceName      string `xml:"id,attr"`
    SoftwareVersion string `xml:"version,attr"`
    ElementType     string `xml:"model,attr"`
    Enb             []Enb
}

However when I attempt to run with go run main.go, I get:

ERRO[2018-06-12 09:45:34] parsing failed    error="node snapshot does not exist" filename=/tmp/datain/xyz/123/agg/233443234543.xml

If I take out the Validation of snapshot, the file unmarshals fine. Why is this not finding the node?

  • 写回答

1条回答 默认 最新

  • douyin4875 2018-06-12 14:12
    关注

    Try exporting snapshot and adding a struct tag indicate the name.

    xml.Unmarshal uses reflection to populate the the struct. So, the elements of the struct need to be exported.

    type ConfigXML struct {
        Snapshot []Snapshot `xml:"snapshot"`
        FileName string
    }
    

    See the GoDoc (search for "exported" and check out the example) for additional information about how xml.Unmarshal works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析