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>gre@example.com</Addr>
</Email>
<Email where='work'>
<Addr>gre@work.com</Addr>
</Email>
<Group>
<Value>Friends</Value>
<Value>Squash</Value>
</Group>
<City>Hanga Roa</City>
<State>Easter Island</State>
</Person>
- 2 回答
- 0 关注
- 154 浏览
添加回答
举报