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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?