我正在使用返回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
有人能幫我弄清楚發生了什麼事以及如何解決它嗎?