1 回答

TA貢獻1876條經驗 獲得超5個贊
這個結構 Marshals 到你需要的 XML,只使用 endcoding/xml.Marshal():
type Grantee struct {
? ? Xmlns_xsi? ?string `xml:"xmlns:xsi,attr,omitempty"`? //set namespace prefix explicitly
? ? Xsi_type? ? string `xml:"xsi:type,attr,omitempty"`? ?//set namespace:attr? explicitly
? ? ID? ? ? ? ? string `xml:",omitempty"`
? ? DisplayName string `xml:",omitempty"`
}
g := Grantee{
? ? DisplayName: "rahul.khan",
? ? ID:? ? ? ? ? "xxxx-xx",
? ? Xsi_type:? ? "CanonicalUser",
? ? Xmlns_xsi:? ?"http://www.w3.org/2001/XMLSchema-instance", // set namespace URI as the value of the field
}
gm, err := xml.MarshalIndent(g, "", "? ")
if err != nil {
? ? fmt.Printf("error: %v", err)
? ? return
}
fmt.Printf("%+s\n", gm)
//<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser">
//? <ID>xxxx-xx</ID>
//? <DisplayName>rahul.khan</DisplayName>
//</Grantee>
https://play.golang.org/p/zrVlmktLyZu
請注意, 和xmlns:xsi只是xsi:type設置為顯式屬性名稱,包括冒號。如您所見,如果在命名空間和屬性名稱之間留一個空格,encoding/xml 會進行更改以嘗試清理輸出中的命名空間(例如使用命名空間 URL 的最后一部分作為命名空間前綴:例如XMLSchema-instance) .
- 1 回答
- 0 關注
- 140 瀏覽
添加回答
舉報