Comments (9)
This may be difficult to discern. The zero value could very well be what the user wants stored, and when unmarshalling, there is a value stored in the XML anyway.
There is one case where it makes sense, though: When an optional element or attribute has a default value set, but is not stored in the XML. But can this be detected? I guess it would require a custom Unmarshal method for every type with children?
from go-xml.
After a bit of experimentation, it seems this is even more difficult to solve.
Default values are attached to attributes, not types, so they cannot be handled easily by a type's Unmarshal methods. On top of that, if an attribute is missing in the XML (and hence needs to be replaced by its default value), its Unmarshal method is never called.
I see only two possible solutions:
- Generate Unmarshal methods for every type and set all default values before handling elements and attributes.
- Generate a default initialiser for every type that must be called instead of initialising to the zero value.
from go-xml.
I just had an idea how passing defaults to the (un)marshaller could work:
In a structured type, add custom tags to the the fields. These could then be interpreted by (Un)MarshalText to handle instance specifics, and even constraints.
The downside is that this still requires custom unmarshallers for every type.
A variation of this would be to submit a PR against the core Go XML package and have this implemented on the built-in unmarshallers.
from go-xml.
I created a proposal on the Go issue tracker for such a feature: golang/go#21425
from go-xml.
You've probably thought about this more than I have. Can we do something like this for default values?
func (x *MyType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
// avoid recursing into this method
type T MyType
t := (*T)(x)
// Assign defaults
t.Field1 = "defaultForField1"
t.Field2 = "defaultForField2"
t.Field4 = "defaultForField4"
return d.DecodeElement(t, &start)
}
So if the elements/attributes are in the xml doc, but empty, they will still be put into the Go value as empty, and if they're not present at all, we'll get whatever defaults are set. I dunno if that's the correct behavior according to the XSD spec, but it seems reasonable. See it in action: https://play.golang.org/p/1AevVrEVnJ
from go-xml.
I played around a bit and tried to build a generic default value handler.
But it's not easy. Go's reflection package is giving me headaches.
Simple assignments like above will work for basic types, but custom types (even if they are strings or ints) still require custom handling. Maybe it's better to just call each unmarshaller instead...
from go-xml.
I tested out your approach, it works nicely. Special handling is still required for other field types than string and embedded types.
Something like this:
type ActuateType string
type RepresentationBaseType struct {
Width uint `xml:"width,attr"`
Height uint `xml:"height,attr"`
}
type AdaptationSetType struct {
RepresentationBaseType
Href string `xml:"href,attr"`
Actuate ActuateType `xml:"actuate,attr"`
SubsegmentStartsWithSAP uint `xml:"subsegmentStartsWithSAP,attr"`
}
func (x *AdaptationSetType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
type T AdaptationSetType
t := (*T)(x)
t.Actuate = ActuateType("onRequest")
t.SubsegmentStartsWithSAP = 100
t.RepresentationBaseType.Width = 200
t.RepresentationBaseType.Height = 200
return d.DecodeElement(t, &start)
}
from go-xml.
Your idea about calling the unmarshaller is interesting. I don't think it's what you meant, but what if, for any types that have default attributes, we construct an xml document with those defaults, and unmarshal that into our type before unmarshalling the real input? This can be done at run-time, or during code generation. Given simplified xsd from your example:
<complexType name="adaptationSetType">
<attribute name="width" type="int" default="200"/>
<attribute name="height" type="int" default="200"/>
<attribute name="subsegmentStartsWithSAP" type="unsignedInt" default="100"/>
</complexType>
We can gen something like this:
type AdaptationSetType struct {
Width uint `xml:"width,attr"`
Height uint `xml:"height,attr"`
SubsegmentStartsWithSAP uint `xml:"subsegmentStartsWithSAP,attr"`
}
var defaultAdaptationSetType AdaptationSetType
func init() {
mustUnmarshal(&defaultAdaptationSetType, `
<AdaptationSetType width="200" height="200" subsegmentStartsWithSAP="100" />`)
}
func mustUnmarshal(v interface{}, xmldoc string) {
if err := xml.Unmarshal(v, []byte(xmldoc)); err != nil {
panic(err)
}
}
func (x *AdaptationSetType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
type T defaultAdaptationSetType
t := (*T)(x)
*t = T(defaultAdaptationSetType)
return d.DecodeElement(t, &start)
}
I'd like to create the default type declaration during code-generation and avoid the run-time panic, but it seems really complicated; we'd have to generate, compile and run a helper program that does the unmarshal of the defaults into our type, and prints it out using fmt.Printf("%#v"), then use that output in the final program.
That said, I think you can only specify simpleTypes for defaults. We can reduce them to builtins and generate separate code for the various types of assignments:
- quoted scalar (string, NMTOKEN, etc)
- unquoted scalar (int, uint, float, double, bool etc)
xml.Name
(QName), could be tricky- list types like
[]string
,[]int
,[]float32
, etc time.Time
(dateTime, gMonth etc)[]byte
from go-xml.
An interesting idea...
Another possible approach would be a simple constructor for each type that prefills fields with their default values. This may even avoid custom UnmarshalXML methods. Care must be taken, however, that this constructor is called when unmarshalling array elements.
I currently use the decoder like this:
func Decode() (*MPDtype, error) {
decoder := xml.NewDecoder(reader)
mpd := &MPDtype{}
err := decoder.Decode(mpd)
return mpd, err
}
This could be turned into:
func NewMPDtype() *MPDtype {
t := &MPDtype{}
// prefill defaults here
return t
}
func Decode() (*MPDtype, error) {
decoder := xml.NewDecoder(reader)
mpd := NewMPDtype()
err := decoder.Decode(mpd)
return mpd, err
}
from go-xml.
Related Issues (20)
- Add "Code generated ..." comment line automatically HOT 1
- Allow wsdlgen to take build tags HOT 2
- xsdgen: gen type "measResults": Unknown built-in type "anySimpleType" HOT 6
- Timezone is not considered in MarshalText method HOT 4
- Schema with restriction and base="xsd:dateTime" HOT 1
- Unable to unmarshal embedded xhtml HOT 3
- could not find base type anySimpleType in namespace http://www.w3.org/2001/XMLSchema HOT 3
- Cannot use non-namespaced (but included) types in schema HOT 4
- complexType DetailedHashSum: could not find type "BinaryDataType" in namespace http://service.ddex.net/xml/avs/avs for element DataType HOT 3
- complexType localElement: could not find type in namespace for attribute substitutionGroup HOT 11
- utf-8 name in xsd HOT 3
- Issue with `type="xsd:date" maxOccurs="unbounded"` HOT 1
- Failed to parse chardata. HOT 2
- Element ref not generating and linking types correctly. HOT 3
- question about walking the xsd HOT 3
- Does not generate code HOT 1
- Tests generated for `gentests/books/books_test.go` do not pass
- replace rule not working to create shared types
- aqwari.net is down HOT 1
- xsdgen problem with string
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from go-xml.