XML-Parser default values

1,226 views
Skip to first unread message

kuli...@gmail.com

unread,
Jun 23, 2013, 7:47:20 AM6/23/13
to golan...@googlegroups.com
I want to parse an xml file.
It has a number of "submesh" tags.
Each submesh tag has the optional attribute "usesharedvertices" which defaults to true, if the parameter is omitted.
When parsing like this
var result MyXMLClass
err := xml.Unmarshal(data, &result)
 it defaults to false.
I can't set all values to true beforehand however, since i don't know how many submesh tags there will be.
Is there an easy way like
type Submesh struct {
    UsesSharedVertices bool `xml:"usesharedvertices;default:true"`
}
which the xml-Parser understands and uses?
Or how do i solve this? 

Kuli Kugelschreiber

unread,
Jun 28, 2013, 4:42:36 PM6/28/13
to golan...@googlegroups.com

Since this functionality didn't seem available, I implemented it myself.

Example of the usage:

type Foo struct { 
      Bar bool `xml:"bar,attr" default:"true"`
}
 
Whenever the attribute bar is ommited, it will be set to true by the parser.
This works for any native type (and pointers).

In case anyone needs it, here is what i did.

(Changes in the following files (as of golang 1.1))


encoding/xml/typeinfo.go


Added field default Value to type fieldInfo:

type fieldInfo struct {
idx     []int
name    string
xmlns   string
defaultValue string
flags   fieldFlags
parents []string
}


Added assignement to default value in func structFieldInfo()

...
if i := strings.Index(tag, " "); i >= 0 {
finfo.xmlns, tag = tag[:i], tag[i+1:]
}
finfo.defaultValue = f.Tag.Get("default")
// Parse flags.
tokens := strings.Split(tag, ",")
... 


encoding/xml/read.go


Added initial assignment to the default value where applicable

in func (p *Decoder) unmarshal(val reflect.Value, start *StartElement) error:

...
for i := range tinfo.fields {
finfo := &tinfo.fields[i]
if finfo.defaultValue != "" {
copyValue(finfo.value(sv), []byte(finfo.defaultValue))
}
switch finfo.flags & fMode {
... 

Reply all
Reply to author
Forward
0 new messages