Warm tip: This article is reproduced from serverfault.com, please click

go-解组时将XML标记解析为布尔值(如果存在)

(go - Parse XML tag to boolean if it exists when unmarshalling)

发布于 2020-11-28 12:24:08

我正在尝试将XML标记解析为布尔值(如果存在)。该标签内<status>可以<active /><available />或者<invalid />只有这些标记的一个内部存在<status>

这是我目前的尝试:

package main

import (
    "encoding/xml"
    "fmt"
)

type Response struct {
    XMLName      xml.Name `xml:"domain"`
    Authority    string   `xml:"authority,attr"`
    RegistryType string   `xml:"registryType,attr"`
    EntityClass  string   `xml:"entityClass,attr"`
    EntityName   string   `xml:"entityName,attr"`
    DomainName   string   `xml:"domainName"`
    Status       Status   `xml:"status"`
}

type Status struct {
    Active    bool `xml:"active,omitempty"`
    Available bool `xml:"available,omitempty"`
    Invalid   bool `xml:"invalid,omitempty"`
}

func main() {

    str := `
<domain authority="domain.fi" registryType="dchk1" entityClass="domain-name" entityName="esimerkki.fi">
  <domainName>esimerkki.fi</domainName>
  <status>
    <active />
  </status>
</domain>
`

    var ans Response
    err := xml.Unmarshal([]byte(str), &ans)
    if err != nil {
        panic(err)
    }

    fmt.Printf(`%#v`, ans.Status)
}

这将全部返回Status.*false而不是Status.Active = true按预期返回你如何获得预期的结果?

指针的第二次尝试:

type Status struct {
    Active    *bool `xml:"active,omitempty"`
    Available *bool `xml:"available,omitempty"`
    Invalid   *bool `xml:"invalid,omitempty"`
}

*ans.Status.Active还是false

Questioner
raspi
Viewed
11
raspi 2020-11-28 21:56:45

作为@ MH-cbon建议简单地检查,如果指针不nil*bool足以确定该标签的存在。但是我去了,然后将XML响应结构转换为Response仅包含所需信息Status的常量结构,并将其转换为常量。

所以现在是:

// Raw XML DTO
type XmlResponse struct {
    XMLName      xml.Name  `xml:"domain"`
    Authority    string    `xml:"authority,attr"`
    RegistryType string    `xml:"registryType,attr"`
    EntityClass  string    `xml:"entityClass,attr"`
    EntityName   string    `xml:"entityName,attr"`
    DomainName   string    `xml:"domainName"`
    Status       XmlStatus `xml:"status"`
}

// Raw XML DTO
type XmlStatus struct {
    Active    *bool `xml:"active,omitempty"`
    Available *bool `xml:"available,omitempty"`
    Invalid   *bool `xml:"invalid,omitempty"`
}

// Return Response struct which doesn't have the unnecessary XML
func (x XmlResponse) GetResponse() Response {
    st := Invalid // Default to invalid

    if x.Status.Active != nil {
        st = Active
    } else if x.Status.Available != nil {
        st = Available
    } else if x.Status.Invalid != nil {
        st = Invalid
    }

    return Response{
        Domain: x.DomainName,
        Status: st,
    }
}

// Proper response parsed from XML
type Response struct {
    Domain string
    Status Status
}

type Status uint8

const (
    Invalid Status = iota
    Active
    Available
)

解析发生为:

var xmlresp XmlResponse
err := xml.Unmarshal([]byte(str), &xmlresp)
if err != nil {
    panic(err)
}

ans := xmlresp.GetResponse()

fmt.Printf(`%#v`, ans)