2017-05-29 81 views
0

在此代碼中,返回的元素x沒有正文 - 我相信MarshalIndent工作不正常。 我將無法使用結構記錄。 是否有任何解決方法,以便它可以按預期返回值。XML元帥不在此示例中

package main 

import "fmt" 
import "encoding/xml" 
import "time" 

type Record struct { 
    a int64  `xml:"a,omitempty"` 
    b int64  `xml:"b,omitempty"` 
    c int64  `xml:"c,omitempty"` 
    d int64  `xml:"d,omitempty"` 
    e int64  `xml:"e,omitempty"` 
    f string `xml:"f,omitempty"` 
    g string `xml:"g,omitempty"` 
    h string `xml:"h,omitempty"` 
    i string `xml:"i,omitempty"` 
    j string `xml:"j,omitempty"` 
    k time.Time `xml:"k,omitempty"` 
    l time.Time `xml:"l,omitempty"` 
    m string `xml:"m,omitempty"` 
    n string `xml:"n,omitempty"` 
    o string `xml:"o,omitempty"` 
    p int64  `xml:"p,omitempty"` 
} 

func main() { 
    temp, _ := time.Parse(time.RFC3339, "") 
    candiateXML := &Record{1, 2, 3, 4, 5, "6", "7", "8", "9", "10", temp, temp, "13", "14", "15", 16} 
    fmt.Printf("%v\n", candiateXML.a) 
    fmt.Printf("%v\n", candiateXML.b) 
    fmt.Printf("%v\n", candiateXML.c) 
    fmt.Printf("%v\n", candiateXML.d) 
    fmt.Printf("%v\n", candiateXML.e) 
    fmt.Printf("%s\n", candiateXML.f) 
    fmt.Printf("%s\n", candiateXML.g) 
    fmt.Printf("%s\n", candiateXML.h) 
    fmt.Printf("%s\n", candiateXML.i) 
    fmt.Printf("%s\n", candiateXML.j) 
    fmt.Printf("%d\n", candiateXML.k) 
    fmt.Printf("%d\n", candiateXML.l) 
    fmt.Printf("%s\n", candiateXML.m) 
    fmt.Printf("%s\n", candiateXML.n) 
    fmt.Printf("%s\n", candiateXML.o) 
    fmt.Printf("%v\n", candiateXML.p) 

    x, err := xml.MarshalIndent(candiateXML, "", " ") 
    if err != nil { 
     return 
    } 
    //why this is not printing properly 
    fmt.Printf("%s\n", x) 
} 

MarshalIndent未返回預期結果。

回答

1

The Go Programming Language Specification

Exported identifiers

的標識符可以被輸出,以允許來自另一個 包訪問它。如果同時輸出標識符:

  1. 標識符名稱的第一個字符是Unicode大寫字母(Unicode類「Lu」);和
  2. 標識符在包塊中聲明,或者它是一個字段名稱或方法名稱。

所有其他標識符不導出。

導出Record結構字段名(第一個字符大寫)以允許從xml包對它們的訪問。例如,

package main 

import "fmt" 
import "encoding/xml" 

type Record struct { 
    A int64 `xml:"a,omitempty"` 
    B int64 `xml:"b,omitempty"` 
    C int64 `xml:"c,omitempty"` 
} 

func main() { 
    candiateXML := &Record{1, 2, 3} 
    fmt.Printf("%v\n", candiateXML.A) 
    fmt.Printf("%v\n", candiateXML.B) 
    fmt.Printf("%v\n", candiateXML.C) 

    x, err := xml.MarshalIndent(candiateXML, "", " ") 
    if err != nil { 
     return 
    } 
    fmt.Printf("%s\n", x) 
} 

輸出:

1 
2 
3 
<Record> 
    <a>1</a> 
    <b>2</b> 
    <c>3</c> 
</Record> 
+0

非常感謝! ++++++++++++++++ –