gostructxml-sitemap

Use duplicate field names in struct to generate XML sitemap


I'm building a sitemap generator in Go. I want to generate the following URL structure to be complaint with the Google sitemap structure.

<url>
    <loc>https://www.website.nl/nl/over-ons</loc>
    <xhtml:link rel="alternate" href="https://www.website.nl/nl/over-ons" hreflang="nl"/>
    <xhtml:link rel="alternate" href="https://www.website.nl/en/about-us" hreflang="en"/>
    <xhtml:link rel="alternate" href="https://www.website.nl/de/uber-uns" hreflang="de"/>
    <changefreq>daily</changefreq>
    <priority>0.7</priority>
    <lastmod>2020-12-05T03:59:58+01:00</lastmod>
</url>

Therefore I created the following struct:

type Url struct {
    Loc         string      `xml:"loc"`
    Link        Link        `xml:"link"`
    Changefreq  string      `xml:"changefreq"`
    Priority    string      `xml:"priority"`
    Lastmod     string      `xml:"lastmod"`
}

type Link struct {
    Rel  string         `xml:"rel,attr,omitempty"`
    Href string         `xml:"href,attr"`
    Hreflang string     `xml:"hreflang,attr"`
}

I cannot figure out how to deal with the link field. Can some help on the following questions?

  1. How can I add three times the same "link" field in the struct?
  2. How to name the field "xhtml:link", I'm getting errors on the : in the name?

Solution

  • If you want to add multiple Link entries just use an array for this:

    Link []Link `xml:"xhtml:link"`