go – Marshal struct array to xml without a parent tag-ThrowExceptions

Exception or error:

I am trying to marshal a go struct with an array into a xml. In this array I need to have a attribute for each element and a value. I do not need this to be inside a parent xml tag.

I have the code below.

package main

import (
    "encoding/xml"
    "fmt"
    "os"
)

func main() {
    type Person struct {
        XMLName   xml.Name `xml:"person"`
        Id        int      `xml:"id,attr"`
        FirstName string
    }

    a := &Person{
       Id: 13,
       FirstName: "John",
    }
    b := &Person{
       Id: 14,
       FirstName: "Doe",
    }
    x := []*Person{}
    x = append(x, a)
    x = append(x, b)

    enc := xml.NewEncoder(os.Stdout)
    enc.Indent("  ", "    ")
    if err := enc.Encode(x); err != nil {
        fmt.Printf("error: %v\n", err)
    }
}

It produces below output.

<person id="13">
  <FirstName>John</FirstName>
</person>
<person id="14">
  <FirstName>Doe</FirstName>
</person>

But I need to make it as below.

<person id="13">John</person>
<person id="14">Doe</person>

Any help on this is much appreciated. Can I do this with go?

How to solve:

Just add xml:",chardata" tag to the FirstName filed:

package main

import (
    "encoding/xml"
    "fmt"
    "os"
)

func main() {
    type Person struct {
        XMLName   xml.Name `xml:"person"`
        ID        int      `xml:"id,attr"`
        FirstName string   `xml:",chardata"`
    }

    a := &Person{
        ID:        13,
        FirstName: "John",
    }
    b := &Person{
        ID:        14,
        FirstName: "Doe",
    }
    x := []*Person{}
    x = append(x, a)
    x = append(x, b)

    enc := xml.NewEncoder(os.Stdout)
    enc.Indent("  ", "    ")
    if err := enc.Encode(x); err != nil {
        fmt.Printf("error: %v\n", err)
    }
}

Output:

<person id="13">John</person>
<person id="14">Doe</person>

Leave a Reply

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