doubi3996 2017-11-28 11:42
浏览 119
已采纳

使用自定义标签解析多个XML文件

I have to parse many XML documents, I already know the logic to parse the files, but the issue is, the tag for each xml file is different.

This is what I have so far

type Data struct {
     Rows []Info `xml:"domain-google.com"` // <- This is custom and needs to change (e.g. the next xml doc tag will be `xml:"domain-facebook.com"`
}

type Info struct {
     Domain string `xml:"domain"`
 }

// example logic for parsing xml

    xmlFile, err := http.Get("somefiles.xml")
    if err != nil { fmt.Println(err) }
    var data Data
    if err = xml.NewDecoder(xmlFile.Body).Decode(&data); err != nil {
        fmt.Println(err)
    }
    for _, rows := range data.Rows {
        fmt.Println(rows.Domain)
    }

example xml documents

<response>
   <!-- This tag is what is custom every time -->
   <domain-google.com>
      <domain>google.com</domain>
   </domain-google.com>
</response>

<response>
   <!-- This tag is what is custom every time -->
   <domain-facebook.com>
      <domain>facebook.com</domain>
   </domain-facebook.com>
</response>

Any idea how to tackle this issue?

Thank you in advanced.

  • 写回答

1条回答 默认 最新

  • douji3623 2017-11-28 14:22
    关注

    As XML goes, this is pretty bad; tag names should not be used for data, only tag bodies and attribute values should hold data. But, all is not lost! Per the documentation on encoding/xml, you can use the ,any tag to map a field that should contain "a sub-element that hasn't matched any of the above rules". You can use this as a sort of wildcard, to match any child element not otherwise mapped - in your case, a child element whose tag name you don't know at compile time:

    type Data struct {
        Rows []Info `xml:",any"`
    }
    

    Playground example: https://play.golang.org/p/lo6bJBRvgV

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

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘