1

XML を返す REST API を使用しており、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>myemail@example.com</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

誰かが何が起こっているのか、それを解決する方法を理解するのを手伝ってくれますか?

4

1 に答える 1