Skip to content

Instantly share code, notes, and snippets.

@nunnatsa
Last active March 10, 2020 14:17
Show Gist options
  • Save nunnatsa/6286663ce51e22bca7ca812085b25789 to your computer and use it in GitHub Desktop.
Save nunnatsa/6286663ce51e22bca7ca812085b25789 to your computer and use it in GitHub Desktop.
package main
/*
Description:
Parsing an NMTOKENS XML tag into a slice of strings
*/
import (
"encoding/xml"
"strings"
"time"
)
// The NMTOKENS type
type Nmtokens []string
// Override default unmarshaling to parse a string from the tag body, into an slice of
// strings
func (t *Nmtokens) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var v string
// Get the tag body as a string
if err := d.DecodeElement(&v, &start); err != nil {
return err
}
*t = strings.Fields(v)
return nil
}
// Override default unmarshaling of attribute
func (t *Nmtokens) UnmarshalXMLAttr(attr xml.Attr) error {
*t = strings.Fields(attr.Value)
return nil
}
// Usage:
/*
Assuming the following XSD schema:
<xs:element name="postMetadata">
<xs:complexType>
<xs:sequence>
<xs:element name="labels" type="xs:NMTOKENS"/>
<xs:element name="createDate" type="xs:dateTime"/>
</xs:sequence>
<xs:attribute name="authors" type="xs:NMTOKENS"/>
</xs:complexType>
</xs:element>
*/
type PostMetedata struct {
Authors Nmtokens `xml:"authors,attr"`
Labels Nmtokens `xml:"labels"`
CreateDate time.Time `xml:"createDate"`
}
func main() {
// our XML as a byte array
xmlBytes := []byte(`<xsd:postMetadata authors="someone someone-else">
<labels>programming go-lang XML</labels>
<createDate>2018-07-08T15:52:58Z</createDate>
</postMetadata>`)
var postData PostMetedata
xml.Unmarshal(xmlBytes, &postData)
// Print all labels, each in single line
println("Labels:")
for _, label := range postData.Labels {
println("- " + label)
}
// Print all autors, each in single line
println("Authors:")
for _, author := range postData.Authors {
println("- " + author)
}
}
/*
Output
Labels:
- programming
- go-lang
- XML
Authors:
- someone
- someone-else
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment