3

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

5
  • 1
    I have run your code, and no problem May 20, 2022 at 1:27
  • 1
    @RahmatFathoni Yes, there is indeed no problem to capture the code and run locally If I didn't misunderstand it, he trying to run of the last commented code.
    – Carson
    May 20, 2022 at 2:25
  • 2
    To promote the struct's fields you need to embed the struct type. You can only embed named types, and pointer to named types. Therefore you need to declare the News struct type. Then, to embed the field, you simply declare the field without an explicit field name, i.e. declare the field using only the field's type. This will, however, make the Go struct incompatible with the XML so you will need to add news> to the promoted fields' tags. An alternative would be to declare all fields in the URL struct and use elem1>elem2... in the tags to guide the unmarshaler.
    – mkopriva
    May 20, 2022 at 2:28
  • 2
    ... example.
    – mkopriva
    May 20, 2022 at 2:29
  • 1
    @Carson, i see. You're right. May 20, 2022 at 2:55

1 Answer 1

1

Omit name will embed to self.

example

package main

import "fmt"

type Animal struct {
    Name string
}

type Cat struct {
    Animal // 👈 Omit name
}

type Dog struct {
    A Animal // 👈 have name "A"
}

func main() {
    cat := Cat{Animal{"Kitty"}}
    fmt.Println(cat.Name)        // OK
    fmt.Println(cat.Animal.Name) // OK too
    dog := Dog{Animal{"Snoopy"}}
    // fmt.Println(dog.Name)   // Error: type Dog has no field or method Name
    fmt.Println(dog.A.Name) // OK too
}

go playground


your case

see 👈 are enough (others same as yours.)

package main

import (
    "encoding/xml"
    "fmt"
    "io/ioutil"
    "net/http"
)

type News struct { // 👈 move to here
    Publishdate string `xml:"news>publication_date"` // 👈 Use ">" to tell its parent. https://github.com/golang/go/blob/0a1a092c4b56a1d4033372fbd07924dad8cbb50b/src/encoding/xml/typeinfo.go#L198-L199
    Title       string `xml:"news>title"`
    Summary     string `xml:"news>keywords"`
}

type urlset struct {
    XMLName xml.Name `xml:"urlset"`
    URL     []struct {
        Loc  string `xml:"loc"`
        News `xml:"news"` // 👈 do not give the name
    } `xml:"url"`
}

func getXML(url string) ([]byte, error) {
    resp, err := http.Get(url)
    if err != nil {
        return []byte{}, fmt.Errorf("GET error: %v", err)
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return []byte{}, fmt.Errorf("Status error: %v", resp.StatusCode)
    }

    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return []byte{}, fmt.Errorf("Read body: %v", err)
    }
    return data, nil
}

func main() {

    var URLset urlset
    /* To avoid the link not working in the future, I write the value directly.
    url := "https://www.dw.com/de/news-sitemap.xml"
    if xmlBytes, err := getXML(url); err != nil {
        fmt.Printf("Failed to get XML: %v", err)
    } else {
        xml.Unmarshal(xmlBytes, &URLset)
    }
    */

    xmlBytes := []byte(`
<urlset>
    <url>
        <loc>https://www.dw.com/de/kopf-an-kopf-rennen-bei-parlamentswahl-in-australien/a-61887162</loc>
        <news:news>
            <news:publication>
                <news:name>Deutsche Welle</news:name>
                <news:language>de</news:language>
            </news:publication>
            <news:publication_date>2022-05-21T11:28:55.875Z</news:publication_date>
            <news:title>Kopf-an-Kopf-Rennen bei Parlamentswahl in Australien</news:title>
            <news:keywords>Australien,Parlamentswahl,Scott Morrison,Anthony Albanese,Labor-Partei,Liberale</news:keywords>
        </news:news>
        <image:image>
            <image:loc>https://static.dw.com/image/61872101_403.jpg</image:loc>
            <image:caption>Der australische Premierminister Scott Morrison (r.) und sein Herausforderer, Oppositionsführer Anthony Albanese</image:caption>
        </image:image>
    </url>
    <url>
        <loc>https://www.dw.com/de/ukraine-aktuell-selenskyj-verlangt-entsch%C3%A4digungsfonds/a-61885143</loc>
        <news:news>
            <news:publication>
                <news:name>Deutsche Welle</news:name>
                <news:language>de</news:language>
            </news:publication>
            <news:publication_date>2022-05-21T11:10:21.813Z</news:publication_date>
            <news:title>Ukraine aktuell: Selenskyj verlangt Entschädigungsfonds</news:title>
            <news:keywords>Ukraine,Krieg,Russland,Wolodymyr Selenskyj,Wladimir Putin,Mariupol</news:keywords>
        </news:news>
        <image:image>
            <image:loc>https://static.dw.com/image/61885205_403.jpg</image:loc>
            <image:caption>75. Filmfestival Cannes | Rede von Wolodymyr Selenskyj</image:caption>
        </image:image>
    </url>
<urlset>
`)

    xml.Unmarshal(xmlBytes, &URLset)
    /************************** XML parser *************************/
    for _, URLElement := range URLset.URL {
        /*
           fmt.Println(
               "[Element]:",
               "\nTitle #", URLElement.News.Title,
               "\nPublicationDate #", URLElement.News.Publishdate,
               "\nSummary#", URLElement.News.Summary,
               "\nLoc #", URLElement.Loc, "\n")
        */

        fmt.Println( // 👈 Now, this work!
            "[Element]:",
            "\nTitle #", URLElement.Title,
            "\nPublicationDate #", URLElement.Publishdate,
            "\nSummary#", URLElement.Summary,
            "\nLoc #", URLElement.Loc, "\n")
    }
}

About the XML Namespaces

More Examples

  • ExampleUnmarshal This link is from go/src/encoding/xml/example_test.go In fact, all the examples are easy to understand. So it's good for learning.
5
  • I changed the 'type News struct' to :type News struct { Publishdate string xml:"news>publication_date" Title string xml:"news>title" Summary string xml:"news>keywords" } , added 'news>' part , without this , the solution doesn'twork. And I also checked the playground code that one works right :)
    – Jia
    May 20, 2022 at 22:57
  • do you mind correct this struct definition ? I don't have permission to do that , I will accept the answer after your correction , in case of misleading others
    – Jia
    May 20, 2022 at 22:58
  • Hi @Jia thank you for the reminder. I only noticed that it was working properly. I didn't notice that some values were not presented. I have updated my answer.
    – Carson
    May 21, 2022 at 13:18
  • You are very polite. But I believe that modifications to posts are made in good faith and do not require special permission from the original author. Still, soon you will be able to make changes directly without going through the community again to review your changes. 2,000 reputation: edit questions and answers
    – Carson
    May 21, 2022 at 13:20
  • thank you for the documents ,really helps !
    – Jia
    May 21, 2022 at 23:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.