xml.Unmarshal()
函數的文檔描述了XML文檔和結構之間的映射是如何工作的(由doc of json.Marshal()
補充)。如果你不熟悉結構標籤,請看看這個答案:What are the use(s) for tags in Go?
首先你需要建模XML文檔。請注意,如果您沒有包裝XML元素,那麼這不是1個XML文檔,而是多個,比如您的情況。您有多個<table>
文檔。
你可以這樣他們型號:
type Col struct {
Name string `xml:"name,attr"`
Value string `xml:",chardata"`
}
type Row struct {
Cols []Col `xml:"col"`
}
type Table struct {
Name string `xml:"name,attr"`
Rows []Row `xml:"row"`
}
而且因爲你有多個<table>
元素,最簡單的就是創建一個xml.Decoder()
,並用Decoder.Decode()
通話單獨分析每個(Decoder.Decode()
將嘗試從解析1個XML文檔其源讀者)。
這是它是如何做:
d := xml.NewDecoder(strings.NewReader(data))
for {
var table Table
if err := d.Decode(&table); err != nil {
fmt.Println(err)
break
}
fmt.Printf("%+v\n", table)
}
當有源string
沒有更多的數據,Decoder.Decode()
將報告io.EOF
。具有以下data
串運行上面的鱈魚:
const data = `<table name="table1">
<row>
<col name="col1">value1</col>
<col name="col2">value2</col>
<col name="col3">value3</col>
</row>
<row>
<col name="col1">value4</col>
<col name="col2">value5</col>
<col name="col3">value6</col>
</row>
</table>
<table name="table2">
<row>
<col name="col1">value7</col>
<col name="col2">value8</col>
<col name="col3">value9</col>
<col name="col4">valueA</col>
</row>
</table>`
輸出是:
{Name:table1 Rows:[{Cols:[{Name:col1 Value:value1} {Name:col2 Value:value2} {Name:col3 Value:value3}]} {Cols:[{Name:col1 Value:value4} {Name:col2 Value:value5} {Name:col3 Value:value6}]}]}
{Name:table2 Rows:[{Cols:[{Name:col1 Value:value7} {Name:col2 Value:value8} {Name:col3 Value:value9} {Name:col4 Value:valueA}]}]}
EOF
嘗試它的Go Playground。
感謝。我的第一個問題還不夠清楚,所以我編輯了一些更多細節 –
@LeonardoRossi請參閱編輯。 –