将XML标记解析为布尔值(如果在解组时存在)
我试图将XML标记解析为布尔值(如果存在)。将XML标记解析为布尔值(如果在解组时存在),xml,go,unmarshalling,Xml,Go,Unmarshalling,我试图将XML标记解析为布尔值(如果存在)。中的标记可以是、或,并且中只存在一个标记 以下是我目前的尝试: package main import ( "encoding/xml" "fmt" ) type Response struct { XMLName xml.Name `xml:"domain"` Authority string `xml:"authority,
中的标记可以是
、
或
,并且
中只存在一个标记
以下是我目前的尝试:
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)
}
*ans.Status.Active
仍然false,因为@mh cbon建议只需检查*bool
的指针是否nil
就足以确定该标记是否存在。但是我将XML响应结构转换为适当的response
struct,它只包含所需的信息,并将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)
您是否尝试将活动属性设置为*bool
?如果这样做有效,那么您必须检查nil/non-nil指针,而不是布尔值。@mh cbon现在我有了,也没有了。我想我们误解了。在该剧本中,当标记出现时,属性将设置为其零值(值为false的nil bool)。当标记不存在时,属性设置为nil,表示标记不存在。我认为您无法获取Status.Active=true,除非您实现了一种特殊的解组器类型,但您可以在给定nil/not nil属性的情况下检测是否存在。@mh cbon获取了它,并回答:)
var xmlresp XmlResponse
err := xml.Unmarshal([]byte(str), &xmlresp)
if err != nil {
panic(err)
}
ans := xmlresp.GetResponse()
fmt.Printf(`%#v`, ans)