[英]Golang Unmarshal same level XML elements into array
我有XML,我想將地址信息編組到其on數組中作為結構的一部分:
<customer>
...
<dob>1990-10-01</dob>
<address1>555 Hollywood Blvd</address1>
<city>Hollywood</city>
<state>CA</state>
<zipCode>99999</zipCode>
<alternateAddress1>575 Hollywood St</alternateAddress1>
<alternateCity>Los Angeles</alternateCity>
<alternateState>CA</alternateState>
<alternateZipCode>12345</alternateZipCode>
....
</customer>
我對結構的嘗試:
type Test struct {
CustProfile struct {
DOB string `xml:"birthDate" json:"dob"`
Address []struct {
PrimaryAddress struct {
Street string `xml:"address1" json:"line1"`
City string `xml:"city" json:"city"`
State string `xml:"state" json:"state"`
ZipCode string `xml:"zipCode" json:"zip"`
IsPrimaryAddress string `json:"isPrimaryAddress"`
}
AlternateAddress struct {
Street string `xml:"alternateAddress1" json:"line1"`
City string `xml:"alternateCity" json:"city"`
State string `xml:"alternateState" json:"state"`
ZipCode string `xml:"alternateZipCode" json:"zip"`
IsPrimaryAddress string `json:"isPrimaryAddress"`
}
} `json:"address"`
} `xml:"customer" json:"custProfile"`
}
所以我在這里有幾個問題。 第一個問題是,所有元素都處於同一級別,根據我到目前為止的了解,由於CustProfile結構已經與客戶父元素相關聯,因此我無法引用Address結構中的任何子元素,因為路徑將是customer->?> city,state等 ,由於該路徑不存在,該路徑將始終返回null。
第二個問題是我嘗試為IsPrimaryAddress定義默認字符串的方式。 我試圖做這樣的事情,但出現了未定義的錯誤。
var marshalTest Test
...
marshalTest.CustProfile.Address.PrimaryAddress.IsPrimaryAddress = "Y";
marshalTest.CustProfile.Address.AlternateAddress.IsPrimaryAddress = "N";
是否有可能將XML解組為導致以下結構的結構?
{
"custProfile": {
"dob": "1990-10-01",
"address": [
{
"line1": "555 Hollywood Blvd",
"city": "HOLLYWOOD",
"state": "CA",
"zip": "99999",
"isPrimaryAddress": "Y"
},
{
"line1": "575 Hollywood St",
"city": "LOS ANGELES",
"state": "CA",
"zip": "12345",
"isPrimaryAddress": "N"
}
]
}
我完全不熟悉Go中的XML編碼,而我所能管理的最好的是:
{
"custProfile": {
"dob": "1990-10-01",
"address": null
}
}
任何幫助將不勝感激。 謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.