Home > Software engineering >  Go: promoted fields in nested struct for XML decoding
Go: promoted fields in nested struct for XML decoding

Time:05-22

I have a XML transfered struct as below :

type urlset struct {
    XMLName xml.Name `xml:"urlset"`
    URL     []struct {
        Loc  string `xml:"loc"`
        News struct {
            Publishdate string `xml:"publication_date"`
            Title       string `xml:"title"`
            Summary     string `xml:"keywords"`
        } `xml:"news"`
    } `xml:"url"`
}

What I should do if I want to promote fields in the nested structure News ?

I hope I can directly access News' fields and print the value as below

var URLset urlset
if xmlBytes, err := getXML(url); err != nil {
    fmt.Printf("Failed to get XML: %v", err)
} else {
    xml.Unmarshal(xmlBytes, &URLset)
}
/************************** XML parser *************************/
for _, URLElement := range URLset.URL {
fmt.Println(
    "[Element]:",
    "\nTitle #", URLElement.title,
    "\nPublicationDate #", URLElement.Publishdate,
    "\nSummary#", URLElement.Summary,
        "\nLoc #", URLElement.Loc, "\n")
}

Here is the complete code of mine Go Playground

CodePudding user response:

Omit name will embed to self.

example

package main

import "fmt"

type Animal struct {
    Name string
}

type Cat struct {
    Animal //            
  • Related