2013-08-23 27 views
1

我正在使用返回XML的REST API,並試圖對XML進行解組,並且出現omitempty不起作用的問題。這裏是工作的XML文件的例子:使用指針時omitempty在編碼/ xml中不起作用?

<?xml version='1.0' encoding='UTF-8'?> 
<customer uri="/api/customers/339/" id="339"> 
    <name> 
     <first>Firstname</first> 
     <last>Lastname</last> 
    </name> 
    <email>[email protected]</email> 
    <billing> 
     <address> 
      <address1>123 Main St.</address123> 
      <address2></address2> 
      <city>Nowhere</city> 
      <state>IA</state> 
      <country>USA</country> 
      <zip>12345</zip> 
     </address> 
    </billing> 
</customer> 

下面是一個「壞」記錄的例子

<?xml version='1.0' encoding='UTF-8'?> 
<customer uri="/api/customers/6848/" id="6848"> 
    <name> 
     <first>Firstname</first> 
     <last>Lastname</last> 
    </name> 
    <email/> 
    <billing/> 
</customer> 

現在,我有我的結構設置如下所示:

type Customer struct { 
    ID  int  `xml:"id,attr"` 
    Name *Name `xml:"name,omitempty"` 
    Billing *Billing `xml:"billing,omitempty"` 
} 

type Billing struct { 
    Address *Address `xml:"address,omitempty"` 
} 

type Address struct { 
    address_1 string `xml:",omitempty"` 
    address_2 string `xml:",omitempty"` 
    city  string `xml:",omitempty"` 
    postal string `xml:",omitempty"` 
    country string `xml:",omitempty"` 
} 

type Name struct { 
    first, last string 
} 

當XML遵循第一個示例<billing></billing>的模式時,讀取它工作的所有記錄,但是當它遇到類似於<billing/>的記錄時,它會拋出所有記錄降低錯誤:panic: runtime error: invalid memory address or nil pointer dereference

有人能幫我弄清楚發生了什麼事以及如何解決它嗎?

回答

2

您可能誤解了,omitempty的含義。僅在編組數據時生效。如果您將<billing/>解組到,omitempty指針字段上,它仍會初始化該字段。然後,由於XML元素爲空,因此將不會設置Billing本身的字段。在實踐中,如果你認爲customer.Billing != nil意味着customer.Billing.Address != nil,你會得到觀察到的恐慌。

備註:http://play.golang.org/p/dClkfOVLXh