1

I must be missing something really obvious... Am trying to parse a simple XML file, following the example from ExampleUnmarshal() in here: http://golang.org/src/pkg/encoding/xml/example_test.go

As you'll see at the bottom of this, none of the attributes or child elements are being mapped - either direction - Marshal or Unmarshal. From what I can tell this is almost the exact same thing they are doing in example_test.go above (the only differences I can see are the that types in that test are within the scope of the function - which I tried, makes no diff, and they are using child elements and not attributes - except for id - but per doc name,attr should work afaict).

Code looks like this:

package main

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


type String struct {
    XMLName xml.Name `xml:"STRING"`
    lang  string   `xml:"lang,attr"`
    value  string   `xml:"value,attr"`
}

type Entry struct {
    XMLName xml.Name `xml:"ENTRY"`
    id      string  `xml:"id,attr"`
    strings []String 
}

type Dictionary struct {
    XMLName xml.Name `xml:"DICTIONARY"`
    thetype  string   `xml:"type,attr"`
    ignore  string   `xml:"ignore,attr"`
    entries []Entry  
}

func main() {

    dict := Dictionary{}

    b := []byte(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<DICTIONARY type="multilanguage" ignore="en">
  <ENTRY id="ActionText.Description.AI_ConfigureChainer">
    <STRING lang="en" value="ActionText.Description.AI_ConfigureChainer"/>
    <STRING lang="da" value=""/>
    <STRING lang="nl" value=""/>
    <STRING lang="fi" value=""/>
  </ENTRY>
</DICTIONARY>
`)

    err := xml.Unmarshal(b, &dict)
    if err != nil { panic(err) }

    fmt.Println(dict) // prints: {{ DICTIONARY}   []}

    dict.ignore = "test"

    out, err := xml.MarshalIndent(&dict, "  ", "    ")
    fmt.Println(string(out)) // prints:   <DICTIONARY></DICTIONARY>

    // huh?

}

1 Answer 1

7

You need to Export (Capitalize) your struct fields.

From the encoding/xml Marshall function docs:

The XML element for a struct contains marshalled elements for each of the exported fields of the struct

See Unable to parse a complex json in golang for a related answer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.