XML

Working with XML is very similar to JSON. In fact, as XML and Go share the semantics of capitalizing their public variable names, there's less mapping annotation required, so the struct only requires a single mapping tag:

type EmailMessage struct {
Subject string
Content string
To Email
From Email
Date time.Time `xml:"Sent"`
}

Encoding and decoding are almost identical; obviously, we need to create xml.Encoder and xml.Decoder rather than the JSON counterparts. The only other difference is the method call to set the indenting (only required for pretty printing):

fmt.Println("To XML:")
encoder := xml.NewEncoder(os.Stdout)
encoder.Indent("", " ")
encoder.Encode(email)

And, we can use a web service to provide us with XML to decode (the URL is omitted here for brevity but can be found in this book's source code repository):

stream := readStream(urlOmitted)
defer stream.Close()

email := &EmailMessage{}
xml.NewDecoder(stream).Decode(email)
fmt.Println("Downloaded:", email)

Executing all of the preceding code will give a similar output to the JSON example but with a different format when encoded. Note also that the variable names start with uppercase letters, which is common in XML:

XML data can just as easily be used when communicating with WebServices
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.26.221