2 回答

TA貢獻1895條經驗 獲得超3個贊
對于重復的 XML 標簽,只需在 Go 中使用切片即可。
請參閱這個簡單的示例,它處理您的 XML 輸入,重點是解組<Impression>標簽,然后再次對其進行編組:
type Impression struct {
Id string `xml:"id,attr"`
Content string `xml:",chardata"`
}
type VAST struct {
Impressions []Impression `xml:"Ad>InLine>Impression"`
}
func main() {
v := &VAST{}
if err := xml.Unmarshal([]byte(src), v); err != nil {
panic(err)
}
fmt.Printf("%+v\n\n", v)
if out, err := xml.MarshalIndent(v, "", " "); err != nil {
panic(err)
} else {
fmt.Println(string(out))
}
}
輸出(已包裝,在Go Playground上嘗試):
&{Impressions:[{Id:ft_vast_i Content:http://servedby.fla...[CUT]...1076585830}
{Id:3rdparty Content:} {Id:3rdparty Content:} {Id:3rdparty Content:}
{Id:3rdparty Content:} {Id:3rdparty Content:} {Id:3rdparty Content:}]}
<VAST>
<Ad>
<InLine>
<Impression id="ft_vast_i">http://servedby.fla...[CUT]...1076585830</Impression>
<Impression id="3rdparty"></Impression>
<Impression id="3rdparty"></Impression>
<Impression id="3rdparty"></Impression>
<Impression id="3rdparty"></Impression>
<Impression id="3rdparty"></Impression>
<Impression id="3rdparty"></Impression>
</InLine>
</Ad>
</VAST>

TA貢獻1865條經驗 獲得超7個贊
是的,您可以編組/解組多個具有相同名稱的節點。只需使用切片。
看一下例子中的Email切片encoding/xml:
type Email struct {
Where string `xml:"where,attr"`
Addr string
}
type Address struct {
City, State string
}
type Result struct {
XMLName xml.Name `xml:"Person"`
Name string `xml:"FullName"`
Phone string
Email []Email
Groups []string `xml:"Group>Value"`
Address
}
以及相應的 XML 文檔:
<Person>
<FullName>Grace R. Emlin</FullName>
<Company>Example Inc.</Company>
<Email where="home">
<Addr>[email protected]</Addr>
</Email>
<Email where='work'>
<Addr>[email protected]</Addr>
</Email>
<Group>
<Value>Friends</Value>
<Value>Squash</Value>
</Group>
<City>Hanga Roa</City>
<State>Easter Island</State>
</Person>
- 2 回答
- 0 關注
- 216 瀏覽
添加回答
舉報