如何使用 2 种不同类型的嵌套内容解组 XML 标记?

问题描述 投票:0回答:1

我正在处理一些在单个 XML 标记中包含混合类型数据的 XML。不同类型的内容取决于属性值。我可以解析字符串或嵌套标签,但我不知道如何支持两者。

有没有办法构建结构体以支持基于标签属性值的不同字段类型?

以下是我到目前为止所拥有的:

package main

import (
    "encoding/xml"
    "fmt"
)

type CustomAttribute struct {
    AttributeID string `xml:"attribute-id,attr"`
    Value       string `xml:",chardata"`
}

type Customer struct {
    CustomAttributes []CustomAttribute `xml:"custom-attribute"`
}

func main() {
    xmlData := `
        <customer>
            <custom-attribute attribute-id="shipmentChangelog">
                <value>06/16/2023 9:22:49 AM PST Shipment has been cancelled: 60686167</value>
                <value>06/22/2023 2:19:10 PM PST Product has been removed: {"id":"47606963","pid":"FBS100402080001"}</value>
            </custom-attribute>
            <custom-attribute attribute-id="isCustomerImported">false</custom-attribute>
            <custom-attribute attribute-id="customerName">JohnDoe</custom-attribute>
        </customer>
    `

    var customer Customer
    if err := xml.Unmarshal([]byte(xmlData), &customer); err != nil {
        fmt.Println("Error:", err)
        return
    }

    // Print the unmarshaled data
    for _, attr := range customer.CustomAttributes {
        fmt.Printf("Attribute ID: %s\n", attr.AttributeID)
        fmt.Printf("Value: %s\n", attr.Value)
    }
}
xml go unmarshalling
1个回答
0
投票

您可以寻求更复杂的解决方案,但也许可以添加:

    Values      []string `xml:"value"`

CustomAttribute
就够了吗?

© www.soinside.com 2019 - 2024. All rights reserved.