Created
October 31, 2018 02:04
-
-
Save justinpage/4f19c2981932caa71cd45fd9e6a21f61 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "encoding/xml" | |
| "fmt" | |
| "os" | |
| ) | |
| type Post struct { | |
| XMLName xml.Name `xml:"post"` | |
| Id string `xml:"id,attr"` | |
| Content string `xml:"content"` | |
| Author Author `xml:"author"` | |
| Xml string `xml:",innerxml"` | |
| } | |
| type Author struct { | |
| Id string `xml:"id,attr"` | |
| Name string `xml:",chardata"` | |
| } | |
| func main() { | |
| post := Post{ | |
| Id: "1", | |
| Content: "Hello World", | |
| Author: Author{ | |
| Id: "2", | |
| Name: "Justin Page", | |
| }, | |
| } | |
| xmlFile, err := os.Create("1.post-by-encode.xml") | |
| if err != nil { | |
| fmt.Println("Error creating XML file:", err) | |
| return | |
| } | |
| _, err = xmlFile.Write([]byte(xml.Header)) | |
| if err != nil { | |
| fmt.Println("Error writing to XML file:", err) | |
| return | |
| } | |
| encoder := xml.NewEncoder(xmlFile) | |
| encoder.Indent("", "\t") | |
| err = encoder.Encode(&post) | |
| if err != nil { | |
| fmt.Println("Error encoding XML to file:", err) | |
| return | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment