How to serialize go struct to XML using one field as a tag and other as a value-ThrowExceptions

Exception or error:

I have some struct:

type Tokens struct {
}

type Token struct {
Type string
Value string
}

I need to get XML file as the output:
<tokens>
<keyword> x</keyword>
<identifier> y </identifier>
<symbol> z </symbol>
</tokens>

Where keyword, identifier or symbol are values of the field Type and x,y,x are values of the field Value

Specifically, I don’t need to wrap each token into tags. There are multiple types of token but for certain value only one type.

The standard library encoding/xml doesn’t provide a ready solution for that. It seems to provide only the ability to use the field name as a tag

How to solve:

You can use encoding/xml. ie:

package main

import (
    "encoding/xml"
    "fmt"
)

func main() {
    type Token struct {
        Keyword    string `xml:"Keyword"`
        Identifier string `xml:"Identifier"`
        Symbol     string `xml:"Symbol"`
    }
    type Tokens struct {
        Tokens []Token `xml:"Token"`
    }
    data := Tokens{[]Token{Token{Keyword: "x", Identifier: "y", Symbol: "z"},
        Token{Keyword: "x1", Identifier: "y1", Symbol: "z1"},}}

    xml, _ := xml.MarshalIndent(data, "","   ")
    fmt.Println(string(xml))
}

Answer´╝Ü

I have solved this using “github.com/beevik/etree” package. They provide easy way to do that

package main

import (
    "os"
    "github.com/beevik/etree"
)

type Token struct {
    Type string
    Value string
}


var x = Token{Type: "keyword", Value: "x",} 
var y = Token{Type: "identifier", Value: "y"}
var z = Token{Type: "symbol", Value: "z"} 
var w = []Token {x, y, z}

func main() {
    doc := etree.NewDocument()
    doc.CreateProcInst("xml", `version="1.0" encoding="UTF-8"`)
    tokens := doc.CreateElement("tokens")

    for i := range w {
        elem := tokens.CreateElement(w[i].Type)
        elem.CreateText(w[i].Value)
    }
    doc.Indent(2)
    doc.WriteTo(os.Stdout)
}

Leave a Reply

Your email address will not be published. Required fields are marked *