douqiao6015 2016-12-14 13:38
浏览 26
已采纳

具有golang属性的xml文档

I have an XML document which looks like this

<?xml version="1.0"?>
<!DOCTYPE venue SYSTEM "z.dtd">
<venue>
<c>
    <a n="k1"><i>0</i></a>
    <a n="k2"><b v="f"/></a>
</c>
</venue>

I would like to extract k1 (integer) , 0 and also k2 (bool) , false

How can I do this with "encoding/xml" ?

  • 写回答

1条回答 默认 最新

  • dongqiaozhe5070 2016-12-14 15:50
    关注

    You have to model your XML structure with Go structs.

    For elements which may have varying content (child elements), one option is to list all possible variations, and only the encountered element will be unmarshaled.

    Your XML structure can be modeled like this:

    type Venue struct {
        As []A `xml:"c>a"`
    }
    
    type A struct {
        N string `xml:"n,attr"`
        I I      `xml:"i"`
        B B      `xml:"b"`
    }
    
    type I struct {
        I int `xml:",chardata"`
    }
    
    type B struct {
        V bool `xml:"v,attr"`
    }
    

    And code to unmarshal the XML document:

    func main() {
        var v Venue
        err := xml.Unmarshal([]byte(data), &v)
        fmt.Printf("%+v %v", v, err)
    }
    
    const data = `<?xml version="1.0"?>
    <!DOCTYPE venue SYSTEM "z.dtd">
    <venue>
    <c>
        <a n="k1"><i>1</i></a>
        <a n="k2"><b v="f"/></a>
    </c>
    </venue>`
    

    Output (try it on the Go Playground):

    {As:[{N:k1 I:{I:1} B:{V:false}} {N:k2 I:{I:0} B:{V:false}}]} <nil>
    

    As you can see, the first element of the Venue.As slice has A.N=k1, and it has the A.I.I=1 value, which was taken from the XML.

    The second element of the Venue.As slice has A.N=k2, and it has the A.B.V=false value, taken from the XML.

    If it bothers you that the "wrapper" A struct contains both the I and the B fields (even though only one of them contains valid data), you may declare them to be pointers, and the one that is not present in the XML will be nil (making it obvious and easy to tell which element was present in the XML):

    type A struct {
        N string `xml:"n,attr"`
        I *I     `xml:"i"`
        B *B     `xml:"b"`
    }
    

    Output this time (try it on the Go Playground):

    {As:[{N:k1 I:0x1050e24c B:<nil>} {N:k2 I:<nil> B:0x1050e2f5}]} <nil>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看