doujishao8793 2014-10-13 08:21
浏览 33
已采纳

将XML解组为struct

I have this xml file and i it seems i cant unmarshal any data into a struct. Someone can help me out here. Its just i never used xml before, always prefered json before xml. Just edited this post with my code and it still gives me empty struct values

<Envelope>
<Data>
        <Order>
            <DeliveryData>
                <del_country>BELGIQUE/BELGIE</del_country>
                <del_country_code>BE</del_country_code>
                <del_company>False</del_company>
                <del_name>ADAM</del_name>
                <del_contact></del_contact>
                <del_firstName></del_firstName>
                <del_addressLine1>Durasweg 33</del_addressLine1>
                <del_addressLine2></del_addressLine2>
                <del_areaCode>1000</del_areaCode>
                <del_city>BRUXELLES</del_city>
                <del_country>BE</del_country>
                <del_language>FR</del_language>
                <del_modeCode>71</del_modeCode>
                <phone1>0032872180808</phone1> 
                <email></email>
                <inv_third>438802</inv_third>
                <OrderID>15787978</OrderID>
                <ParcelID>NE1578797801</ParcelID>
                <OrderDate>16/09/2014 14:22:54</OrderDate>
                <Shipping_date>16/09/2014 14:26:55</Shipping_date>
            </DeliveryData>
    </Order>
  </Data>

 type DeliveryData struct {
    XMLName xml.Name `xml:"DeliveryData"`
    Country string   `xml:"del_country"`
}

type Envelope struct {
    XMLName xml.Name `xml:"Envelope"`
    Data    Data     `xml:"Data"`
}

type Data struct {
    XMLName xml.Name `xml:Data`
    Orders  []Order  `xml:Order`
}

type Order struct {
    XMLName      xml.Name     `xml:"Order"`
    DeliveryData DeliveryData `xml:"DeliveryData"`
}
  • 写回答

2条回答 默认 最新

  • dpdhsq0783 2014-10-13 11:02
    关注

    There are two reasons:

    1. Your XML is malformed - you should add a closing </Envelope>.
    2. Your struct tags in Data are malformed – they don't quote the name of the attribute - this means the the XML deserializer looks for an 'Order' field, instead of the Orders field.

    For good measure: you can find a fully working example on http://play.golang.org/p/6-odOcSOnF

    The relevant part is my

    type Data struct {
        XMLName xml.Name `xml:"Data"`
        Orders  []Order  `xml:"Order"`
    }
    

    versus your original

    type Data struct {
        XMLName xml.Name `xml:Data`
        Orders  []Order  `xml:Order`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥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 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看