首页 > 代码库 > xml格式化写入文件

xml格式化写入文件

参考xml文件地址:http://cloudprint.cainiao.com/template/standard/101

代码:

package mainimport (    "encoding/xml"    "fmt"    "os"    "time")type xmldas struct {    XMLName           xml.Name       `xml:"page"`    Xmlns             string         `xml:"xmlns,attr"`    XmlnsXsi          string         `xml:"xmlns:xsi,attr"`    XsiSchemaLocation string      `xml:"xsi:schemaLocation,attr"`    XmlnsEditor       string        `xml:"xmlns:editor,attr"`    Width             string         `xml:"width,attr"`    Height            string        `xml:"height,attr"`    Auth              xmlAuth        `xml:"auth"`}type xmlAuth struct {    Name string `xml:name`    Age  int `xml:age`}func main() {    v := xmldas{Xmlns:"http://cloudprint.cainiao.com/print", XmlnsXsi:"http://www.w3.org/2001/XMLSchema-instance", XsiSchemaLocation:"http://cloudprint.cainiao.com/print http://cloudprint-docs-resource.oss-cn-shanghai.aliyuncs.com/lpml_schema.xsd", XmlnsEditor:"http://cloudprint.cainiao.com/schema/editor", Width:"100", Height:"180" }    v.Auth = xmlAuth{Name:"ha666", Age:32}    output, err := xml.MarshalIndent(v, "", "\t")    if err != nil {        fmt.Printf("error: %v\n", err)    }    filename := time.Now().Format("2006-01-02-15-04-05")    userFile := filename + ".xml"    fout, err := os.Create(userFile)    defer fout.Close()    if err != nil {        fmt.Println(userFile, err)        return    }    fout.Write([]byte(xml.Header))    fout.Write(output)    fout.Close()}

 

生成的xml:

<?xml version="1.0" encoding="UTF-8"?><page xmlns="http://cloudprint.cainiao.com/print" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://cloudprint.cainiao.com/print http://cloudprint-docs-resource.oss-cn-shanghai.aliyuncs.com/lpml_schema.xsd" xmlns:editor="http://cloudprint.cainiao.com/schema/editor" width="100" height="180">    <auth>        <Name>ha666</Name>        <Age>32</Age>    </auth></page>

 

xml格式化写入文件