Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
correctly handling optional xml elements in golang
Browse files Browse the repository at this point in the history
geoko86 committed Jan 23, 2023
1 parent 4b677f0 commit 3654841
Showing 2 changed files with 10 additions and 1 deletion.
6 changes: 5 additions & 1 deletion genGo.go
Original file line number Diff line number Diff line change
@@ -218,11 +218,15 @@ func (gen *CodeGenerator) GoComplexType(v *ComplexType) {
if element.Plural {
plural = "[]"
}
var optional string
if element.Optional {
optional = `,omitempty`
}
fieldType := genGoFieldType(getBasefromSimpleType(trimNSPrefix(element.Type), gen.ProtoTree))
if fieldType == "time.Time" {
gen.ImportTime = true
}
content += fmt.Sprintf("\t%s\t%s%s\t`xml:\"%s\"`\n", genGoFieldName(element.Name, false), plural, fieldType, element.Name)
content += fmt.Sprintf("\t%s\t%s%s\t`xml:\"%s%s\"`\n", genGoFieldName(element.Name, false), plural, fieldType, element.Name, optional)
}
if len(v.Base) > 0 {
// If the type is a built-in type, generate a Value field as chardata.
5 changes: 5 additions & 0 deletions xmlElement.go
Original file line number Diff line number Diff line change
@@ -48,6 +48,11 @@ func (opt *Options) OnElement(ele xml.StartElement, protoTree []interface{}) (er
e.Plural = true
}
}
if attr.Name.Local == "minOccurs" {
if attr.Value == "0" {
e.Optional = true
}
}
}

if e.Type == "" {

0 comments on commit 3654841

Please sign in to comment.