dongzaijiao4863 2016-01-18 19:55
浏览 64
已采纳

带有重复标记的xml解析

When an xml feed has multiple tags within a structure I am having issues parsing it:

<feed>
<entry>
:
:
</entry>
<entry>
:
:

</entry>
</feed>

In this case I have no issues parsing the entry by defining an array of []entries However one of the entries is a geocode tag which has valuename and value tag repeated twice. How does one define a structure in such a case.?

<geocode>
<valueName>abc</valueName>
<value>a1</value>
<valueName>def</valueName>
<value>d1</value>
</geocode>

Here is the go program that I am having issues with https://play.golang.org/p/SE8RXTNbYl

  • 写回答

1条回答 默认 最新

  • dongzhang6544 2016-01-18 20:27
    关注

    If you have multiple tags with the same name under the same parent tag, you can always use a slice which will hold all the occurrences of the tag, regardless if they are enumerated next to each other or there are other tags between them.

    To be complete, this is the XML fragment you want to parse:

    <cap:geocode>
        <valueName>FIPS6</valueName>
        <value>002090 002290</value>
        <valueName>UGC</valueName>
        <value>AKZ222</value>
    </cap:geocode>
    

    So simply change your geocode struct from this:

    type geocode struct {
        ValueName1 string `xml:"valueName"`
        Value1     string `xml:"value"`
        ValueName2 string `xml:"valueName"`
        Value2     string `xml:"value"`
    }
    

    To this:

    type geocode struct {
        ValueNames []string `xml:"valueName"`
        Values     []string `xml:"value"`
    }
    

    And code to print them:

    gc := v.Entries[0].Geocode
    log.Println(len(gc.Values))
    log.Println(gc.ValueNames)
    log.Println(gc.Values)
    for i := range gc.Values {
        fmt.Printf("ValueName=%s, Value=%s
    ", gc.ValueNames[i], gc.Values[i])
    }
    

    Output (try your modified source on the Go Playground):

    2009/11/10 23:00:00 2
    2009/11/10 23:00:00 [FIPS6 UGC]
    2009/11/10 23:00:00 [002090 002290 AKZ222]
    ValueName=FIPS6, Value=002090 002290
    ValueName=UGC, Value=AKZ222
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码