func (ccs *CampaignCriterions) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error { cc := NegativeCampaignCriterion{} for token, err := dec.Token(); err == nil; token, err = dec.Token() { if err != nil { return err } switch start := token.(type) { case xml.StartElement: switch start.Name.Local { case "campaignId": if err := dec.DecodeElement(&cc.CampaignId, &start); err != nil { return err } case "criterion": criterion, err := criterionUnmarshalXML(dec, start) if err != nil { return err } cc.Criterion = criterion case "bidModifier": if err := dec.DecodeElement(&cc.BidModifier, &start); err != nil { return err } case "isNegative": if err := dec.DecodeElement(&cc.IsNegative, &start); err != nil { return err } } } } *ccs = append(*ccs, cc) return nil }
// readSheetsFromZipFile is an internal helper function that loops // over the Worksheets defined in the XSLXWorkbook and loads them into // Sheet objects stored in the Sheets slice of a xlsx.File struct. func readSheetsFromZipFile(f *zip.File, file *File, sheetXMLMap map[string]string) ([]*Sheet, []string, error) { var workbook *xlsxWorkbook var error error var rc io.ReadCloser var decoder *xml.Decoder var sheetCount int workbook = new(xlsxWorkbook) rc, error = f.Open() if error != nil { return nil, nil, error } decoder = xml.NewDecoder(rc) error = decoder.Decode(workbook) if error != nil { return nil, nil, error } sheetCount = len(workbook.Sheets.Sheet) sheets := make([]*Sheet, sheetCount) names := make([]string, sheetCount) sheetChan := make(chan *indexedSheet, sheetCount) for i, rawsheet := range workbook.Sheets.Sheet { go readSheetFromFile(sheetChan, i, rawsheet, file, sheetXMLMap) } for j := 0; j < sheetCount; j++ { sheet := <-sheetChan if sheet.Error != nil { return nil, nil, sheet.Error } sheets[sheet.Index] = sheet.Sheet names[sheet.Index] = workbook.Sheets.Sheet[sheet.Index].Name } return sheets, names, nil }
// getWorksheetFromSheet() is an internal helper function to open a // sheetN.xml file, refered to by an xlsx.xlsxSheet struct, from the XLSX // file and unmarshal it an xlsx.xlsxWorksheet struct func getWorksheetFromSheet(sheet xlsxSheet, worksheets map[string]*zip.File, sheetXMLMap map[string]string) (*xlsxWorksheet, error) { var rc io.ReadCloser var decoder *xml.Decoder var worksheet *xlsxWorksheet var error error var sheetName string worksheet = new(xlsxWorksheet) sheetName, ok := sheetXMLMap[sheet.Id] if !ok { if sheet.SheetId != "" { sheetName = fmt.Sprintf("sheet%s", sheet.SheetId) } else { sheetName = fmt.Sprintf("sheet%s", sheet.Id) } } f := worksheets[sheetName] rc, error = f.Open() if error != nil { return nil, error } decoder = xml.NewDecoder(rc) error = decoder.Decode(worksheet) if error != nil { return nil, error } return worksheet, nil }
// readSharedStringsFromZipFile() is an internal helper function to // extract a reference table from the sharedStrings.xml file within // the XLSX zip file. func readSharedStringsFromZipFile(f *zip.File) (*RefTable, error) { var sst *xlsxSST var error error var rc io.ReadCloser var decoder *xml.Decoder var reftable *RefTable // In a file with no strings it's possible that // sharedStrings.xml doesn't exist. In this case the value // passed as f will be nil. if f == nil { return nil, nil } rc, error = f.Open() if error != nil { return nil, error } sst = new(xlsxSST) decoder = xml.NewDecoder(rc) error = decoder.Decode(sst) if error != nil { return nil, error } reftable = MakeSharedStringRefTable(sst) return reftable, nil }
func (self *Definitions) UnmarshalXML(d *xml.Decoder, start xml.StartElement) (err error) { err = d.DecodeElement(&self.InnerDefinitions, &start) if err != nil { return } self.XMLName = start.Name self.Aliases = map[string]string{} self.Types.Schemas = xsd.SchemaMap{} for _, schema := range self.Types.Schemata { self.Types.Schemas[schema.TargetNamespace] = schema } for _, attr := range start.Attr { if _, ok := self.Aliases[attr.Name.Local]; !ok { self.Aliases[attr.Name.Local] = attr.Value } for k := range self.Types.Schemas { if _, ok := self.Types.Schemas[k].Aliases[attr.Name.Local]; !ok { self.Types.Schemas[k].Aliases[attr.Name.Local] = attr.Value } } } return }
func (agcs *AdGroupCriterions) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error { adGroupCriterionType, err := findAttr(start.Attr, xml.Name{ Space: "http://www.w3.org/2001/XMLSchema-instance", Local: "type"}) if err != nil { return err } switch adGroupCriterionType { case "BiddableAdGroupCriterion": bagc := BiddableAdGroupCriterion{} err := dec.DecodeElement(&bagc, &start) if err != nil { return err } *agcs = append(*agcs, bagc) case "NegativeAdGroupCriterion": nagc := NegativeAdGroupCriterion{} err := dec.DecodeElement(&nagc, &start) if err != nil { return err } *agcs = append(*agcs, nagc) default: if StrictMode { return fmt.Errorf("unknown AdGroupCriterion -> %#v", adGroupCriterionType) } } return nil }
func (p *Problem) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { pp := struct { Id string `xml:"id"` Name string `xml:"name"` Available string `xml:"available"` ProblemTimeLimit string `xml:"problemtimelimit"` ProblemMemoryLimit string `xml:"problemmemorylimit"` Status Status `xml:"status"` SolvedList []SolvedUser `xml:"solved_list>user"` }{} if err := d.DecodeElement(&pp, &start); err != nil { return err } available, err := strconv.Atoi(strings.Trim(pp.Available, "\n")) problemTimeLimit, err := strconv.Atoi(strings.Trim(pp.ProblemTimeLimit, "\n")) problemMemoryLimit, err := strconv.Atoi(strings.Trim(pp.ProblemMemoryLimit, "\n")) if err != nil { return err } *p = Problem{ Id: strings.Trim(pp.Id, "\n"), Name: strings.Trim(pp.Name, "\n"), Available: available, ProblemTimeLimit: problemTimeLimit, ProblemMemoryLimit: problemMemoryLimit, Status: pp.Status, SolvedList: pp.SolvedList, } return nil }
// UnmarshalXML implements the XML Unmarshaler interface func (s *Show) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { nfo := showFields{} if err := d.DecodeElement(&nfo, &start); err != nil { return err } s.Title = nfo.Title s.Rating = nfo.Rating s.Plot = nfo.Plot s.URL = nfo.URL s.TvdbID = nfo.TvdbID s.ImdbID = nfo.ImdbID s.Year = nfo.Year if nfo.Premiered != "" { firstAired, err := time.Parse("2006-01-02", nfo.Premiered) if err != nil { return err } s.FirstAired = &firstAired } return nil }
// SEE http://play.golang.org/p/EFXZNsjE4a and // http://stackoverflow.com/questions/17301149/golang-xml-unmarshal-and-time-time-fields func (c *customTime) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { var v string d.DecodeElement(&v, &start) parse, _ := time.Parse(TimeFormat, v) *c = customTime{parse} return nil }
func getArrayValue(parser *xml.Decoder) (result interface{}, err error) { var token xml.Token token, err = parser.Token() result = []interface{}{} for { switch t := token.(type) { case xml.StartElement: if t.Name.Local == "value" { var value interface{} value, err = getValue(parser) result = append(result.([]interface{}), value) } case xml.EndElement: if t.Name.Local == "array" { return result, err } } token, err = parser.Token() } return }
func XMLText(decoder *xml.Decoder) (string, error) { r := "" for { token, err := decoder.Token() if err == io.EOF { return r, io.EOF } switch token := token.(type) { case xml.EndElement: return r, nil case xml.CharData: r += string(token) case xml.StartElement: sub, err := XMLText(decoder) r += sub if err != nil { return r, err } case xml.Comment: // ignore case xml.ProcInst: // ignore case xml.Directive: // ignore default: panic("unknown token") } } }
func getStructMember(parser *xml.Decoder) (member Struct) { var token xml.Token token, _ = parser.Token() member = Struct{} for { switch t := token.(type) { case xml.StartElement: if t.Name.Local == "name" { member["name"], _ = getElementValue(parser) } if t.Name.Local == "value" { member["value"], _ = getValue(parser) } case xml.EndElement: if t.Name.Local == "member" { return member } } token, _ = parser.Token() } return }
func (c *choice) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error { for { tok, err := dec.Token() if err != nil && err == io.EOF { return nil } if err != nil { return err } switch v := tok.(type) { case xml.StartElement: switch v.Name.Local { case "description": d := &description{} d.commands = c.commands dec.DecodeElement(d, &v) switch d.Lang { case "en": c.DescriptionEn = d case "de": c.DescriptionDe = d } } } } return nil }
// Scan XML token stream to finc next Element (start or end) func nextElement(p *xml.Decoder) (xml.Token, error) { for { t, err := p.Token() if err != nil { return xml.StartElement{}, err } switch elem := t.(type) { case xml.StartElement, xml.EndElement: return t, nil case xml.CharData: // https://xmpp.org/rfcs/rfc6120.html#xml-whitespace // rfc6120, section 1.4: "whitespace" is used to refer to any character // or characters matching [...] SP, HTAB, CR, or LF. switch string(elem) { case " ", "\t", "\r", "\n": //TODO: consider more than one whitespace log.Println("xmpp: received whitespace ping") } case xml.ProcInst: if !(elem.Target == "xml" && strings.HasPrefix(string(elem.Inst), "version=")) { log.Printf("xmpp: received unhandled ProcInst element: target=%s inst=%s\n", elem.Target, string(elem.Inst)) } default: log.Printf("xmpp: received unhandled element: %#v\n", elem) } } }
func parseFeed(d *xml.Decoder) (v Video, err error) { var feed Feed err = d.Decode(&feed) if err != nil { return } if len(feed.Groups) == 0 || len(feed.Groups[0].Titles) == 0 { err = errors.New("invalid feed") return } group := feed.Groups[0] found := false for _, title := range group.Titles { if title.Type == "plain" { v.Title = title.Value found = true break } } if !found { v.Title = group.Titles[0].Value } v.Duration = time.Duration(group.Duration.Value) * time.Second return }
func readOptiongroup(attributes []xml.Attr, dec *xml.Decoder) *Optiongroup { og := &Optiongroup{} og.ShortDescription = make(map[string]string) forloop: for { t, err := dec.Token() if err != nil { break } switch v := t.(type) { case xml.StartElement: switch v.Name.Local { case "shortdescription": lang, text := readShortDescription(v.Attr, dec) og.ShortDescription[lang] = text case "classoption": og.Classoption = append(og.Classoption, readClassoption(v.Attr, dec)) } case xml.EndElement: if v.Name.Local == "optiongroup" { break forloop } } } return og }
func (c ChoiceParser) ParseList(d *xml.Decoder, start xml.StartElement, containerPtr interface{}, typeofPtr interface{}, appenderType appender) error { typeof := reflect.TypeOf(typeofPtr).Elem() container := reflect.ValueOf(containerPtr).Elem() token, err := d.Token() for token != start.End() { if err != nil { return err } next, ok := token.(xml.StartElement) if ok { item, err := c.Parse(d, next) if err != nil { return err } val := reflect.ValueOf(item) if !val.Type().Implements(typeof) { return fmt.Errorf("Item is not a valid %v.", typeof.Name()) } appendFn := appenders[appenderType] appendFn(container, val) } token, err = d.Token() } return nil }
func readPackageoption(attributes []xml.Attr, dec *xml.Decoder) *Packageoption { po := &Packageoption{} po.ShortDescription = make(map[string]string) for _, attribute := range attributes { switch attribute.Name.Local { case "name": po.Name = attribute.Value case "default": po.Default = attribute.Value == "yes" } } forloop: for { t, err := dec.Token() if err != nil { break } switch v := t.(type) { case xml.StartElement: switch v.Name.Local { case "shortdescription": lang, text := readShortDescription(v.Attr, dec) po.ShortDescription[lang] = text } case xml.EndElement: if v.Name.Local == "packageoption" { break forloop } } } return po }
func (x *XmlNode) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { x.Name = getName(start.Name) x.Attrs = map[string]string{} for _, attr := range start.Attr { x.Attrs[getName(attr.Name)] = attr.Value } token, err := d.Token() for token != start.End() { if err != nil { return err } next, ok := token.(xml.StartElement) if ok { child := XmlNode{} err = child.UnmarshalXML(d, next) if err != nil { return err } x.Children = append(x.Children, child) } else { text, ok := token.(xml.CharData) if ok { x.Children = append(x.Children, TextNode(string([]byte(text)))) } } token, err = d.Token() } return nil }
func readVariant(attributes []xml.Attr, dec *xml.Decoder) Variant { variant := Variant{} variant.Description = make(map[string]template.HTML) for _, attribute := range attributes { if attribute.Name.Local == "name" { variant.Name = attribute.Value } } for { t, err := dec.Token() if err != nil { break } switch v := t.(type) { case xml.StartElement: switch v.Name.Local { case "argument": variant.Arguments = append(variant.Arguments, readArgument(v.Attr, dec)) case "description": lang, text := readDescription(v.Attr, dec) variant.Description[lang] = text } case xml.EndElement: if v.Name.Local == "variant" { return variant } } } return variant }
func (s *SolvedUser) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { ss := struct { Id string `xml:"id"` SubmissionDate string `xml:"submissiondate"` Language string `xml:"language"` CpuTime string `xml:"cputime"` Memory string `xml:"memory"` CodeSize string `xml:"code_size"` }{} if err := d.DecodeElement(&ss, &start); err != nil { return err } submissionDate, _ := strconv.ParseInt(strings.Trim(ss.SubmissionDate, "\n "), 10, 64) cpuTime, _ := strconv.Atoi(strings.Trim(ss.CpuTime, "\n ")) memory, _ := strconv.Atoi(strings.Trim(ss.Memory, "\n ")) codeSize, _ := strconv.Atoi(strings.Trim(ss.CodeSize, "\n ")) *s = SolvedUser{ Id: strings.Trim(ss.Id, "\n "), SubmissionDate: submissionDate, Language: strings.Trim(ss.Language, "\n "), CpuTime: cpuTime, Memory: memory, CodeSize: codeSize, } return nil }
func readShortDescription(attributes []xml.Attr, dec *xml.Decoder) (string, string) { var lang string for _, attribute := range attributes { if attribute.Name.Local == "lang" { lang = attribute.Value } } var str string for { t, err := dec.Token() if err != nil { break } switch v := t.(type) { case xml.CharData: str += string(v) case xml.EndElement: return lang, str default: } } // never reached!?!? return lang, str }
// readWorkbookRelationsFromZipFile is an internal helper function to // extract a map of relationship ID strings to the name of the // worksheet.xml file they refer to. The resulting map can be used to // reliably derefence the worksheets in the XLSX file. func readWorkbookRelationsFromZipFile(workbookRels *zip.File) (WorkBookRels, error) { var sheetXMLMap WorkBookRels var wbRelationships *xlsxWorkbookRels var rc io.ReadCloser var decoder *xml.Decoder var err error rc, err = workbookRels.Open() if err != nil { return nil, err } decoder = xml.NewDecoder(rc) wbRelationships = new(xlsxWorkbookRels) err = decoder.Decode(wbRelationships) if err != nil { return nil, err } sheetXMLMap = make(WorkBookRels) for _, rel := range wbRelationships.Relationships { if strings.HasSuffix(rel.Target, ".xml") && rel.Type == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" { _, filename := path.Split(rel.Target) sheetXMLMap[rel.Id] = strings.Replace(filename, ".xml", "", 1) } } return sheetXMLMap, nil }
// UnmarshalXML appends the property names and values enclosed within start // to ps. // // An xml:lang attribute that is defined either on the DAV:prop or property // name XML element is propagated to the property's Lang field. // // UnmarshalXML returns an error if start does not contain any properties or if // property values contain syntactically incorrect XML. func (ps *proppatchProps) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { lang := xmlLang(start, "") for { t, err := next(d) if err != nil { return err } switch elem := t.(type) { case xml.EndElement: if len(*ps) == 0 { return fmt.Errorf("%s must not be empty", start.Name.Local) } return nil case xml.StartElement: p := Property{ XMLName: t.(xml.StartElement).Name, Lang: xmlLang(t.(xml.StartElement), lang), } err = d.DecodeElement(((*xmlValue)(&p.InnerXML)), &elem) if err != nil { return err } *ps = append(*ps, p) } } }
// UnmarshalXML implements xml.Unmarshaler func (u *UUID) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { var v []byte d.DecodeElement(&v, &start) b := u[:] return decodeUUID(b, v) }
func (freq *Freq) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { var s string if err := d.DecodeElement(&s, &start); err != nil { return err } switch s { case "": *freq = Freq{0} case "always": // Use second as the minimum unit of change frequence *freq = Freq{time.Second} case "hourly": *freq = Freq{time.Hour} case "daily": *freq = Freq{time.Hour * 24} case "weekly": *freq = Freq{time.Hour * 24 * 7} case "monthly": *freq = Freq{time.Hour * 24 * 30} case "yearly": *freq = Freq{time.Hour * 24 * 365} case "never": // time.Duration is int64 *freq = Freq{1<<63 - 1} default: return errors.New("invalid frequence: " + s) } return nil }
// readWorkbookRelationsFromZipFile is an internal helper function to // extract a map of relationship ID strings to the name of the // worksheet.xml file they refer to. The resulting map can be used to // reliably derefence the worksheets in the XLSX file. func readWorkbookRelationsFromZipFile(workbookRels *zip.File) (map[string]string, error) { var sheetXMLMap map[string]string var wbRelationships *xlsxWorkbookRels var rc io.ReadCloser var decoder *xml.Decoder var err error rc, err = workbookRels.Open() if err != nil { return nil, err } decoder = xml.NewDecoder(rc) wbRelationships = new(xlsxWorkbookRels) err = decoder.Decode(wbRelationships) if err != nil { return nil, err } sheetXMLMap = make(map[string]string) for _, rel := range wbRelationships.Relationships { if strings.HasSuffix(rel.Target, ".xml") && strings.HasPrefix(rel.Target, "worksheets/") { sheetXMLMap[rel.Id] = strings.Replace(rel.Target[len("worksheets/"):], ".xml", "", 1) } } return sheetXMLMap, nil }
func NewTree(dec *xml.Decoder) (Node, error) { var stack []*Element // stack of elements var result *Element for { tok, err := dec.Token() if err == io.EOF { break } else if err != nil { return nil, err } switch tok := tok.(type) { case xml.StartElement: newElem := &Element{tok.Name, tok.Attr, []Node{}} if len(stack) > 0 { elem := stack[len(stack)-1] elem.Children = append(elem.Children, newElem) } stack = append(stack, newElem) if result == nil { result = newElem } case xml.EndElement: stack = stack[:len(stack)-1] // pop case xml.CharData: if len(stack) == 0 { continue } elem := stack[len(stack)-1] elem.Children = append(elem.Children, CharData(tok)) } } return result, nil }
// readSheetsFromZipFile is an internal helper function that loops // over the Worksheets defined in the XSLXWorkbook and loads them into // Sheet objects stored in the Sheets slice of a xlsx.File struct. func readSheetsFromZipFile(f *zip.File, file *File) ([]*Sheet, []string, error) { var workbook *xlsxWorkbook var error error var rc io.ReadCloser var decoder *xml.Decoder workbook = new(xlsxWorkbook) rc, error = f.Open() if error != nil { return nil, nil, error } decoder = xml.NewDecoder(rc) error = decoder.Decode(workbook) if error != nil { return nil, nil, error } sheets := make([]*Sheet, len(workbook.Sheets.Sheet)) names := make([]string, len(workbook.Sheets.Sheet)) for i, rawsheet := range workbook.Sheets.Sheet { worksheet, error := getWorksheetFromSheet(rawsheet, file.worksheets) if error != nil { return nil, nil, error } sheet := new(Sheet) sheet.Rows, sheet.MaxCol, sheet.MaxRow = readRowsFromSheet(worksheet, file) sheets[i] = sheet names[i] = rawsheet.Name } return sheets, names, nil }
func extractCombinations(dec *xml.Decoder, terms *[]string) { prefix := "" emitted := false for { token, err := dec.Token() if err != nil { if !emitted && prefix != "" { *terms = append(*terms, prefix) } return } if _, isEnd := token.(xml.EndElement); isEnd { if !emitted && prefix != "" { *terms = append(*terms, prefix) } return } if start, isStart := token.(xml.StartElement); isStart { if start.Name.Local == "indexterm" { emitted = true if prefix != "" { suffix, _ := xmltext(dec) *terms = append(*terms, prefix+":"+suffix) } } else { panic("unhandled keyword:" + start.Name.Local) } } if data, isData := token.(xml.CharData); isData { prefix = string(data) } } }