1 回答

TA貢獻1836條經(jīng)驗 獲得超3個贊
事實證明,目前沒有辦法在 Go 中原生地做到這一點。有一個與命名空間相關(guān)的問題列表,以及描述它的特定問題,但尚未解決。
但是,我也找到了一種解決方法??梢詾閷傩院驮鼐帉懽约旱慕饨M代碼。
對于屬性,您可以實現(xiàn)以下內(nèi)容:
type NonMarshalled string
func (s *NonMarshalled) UnmarshalXMLAttr(attr xml.Attr) error {
fmt.Printf("Parsing attribute '%s', with value '%s'", attr.Name.Local, attr.Value)
s.Title = strings.ToUpper(attr.Value)
return nil
}
type Typemap struct {
XMLName xml.Name `xml:"map"`
Name string `xml:"name,attr"`
Type NonNamespaced `xml:"type,attr"`
XsiType string `xml:"http://www.w3.org/2001/XMLSchema-instance type,attr"`
}
但是,這并不能同時具有命名空間屬性名稱和具有相同名稱的非命名空間屬性。這仍然會導(dǎo)致:
main.Typemap field "Type" with tag "type,attr" conflicts with field "XsiType" with tag "http://www.w3.org/2001/XMLSchema-instance type,attr"
這里的解決方法是為整個Typemap類型編寫一個解組器。就我而言,此代碼如下所示:
func (s *Typemap) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
nameAttr := ""
typeAttr := ""
xsiTypeAttr := ""
for _, attr := range start.Attr {
if attr.Name.Space == "" && attr.Name.Local == "name" {
nameAttr = attr.Value
}
if attr.Name.Space == "" && attr.Name.Local == "type" {
typeAttr = attr.Value
}
if attr.Name.Space == "http://www.w3.org/2001/XMLSchema-instance" && attr.Name.Local == "type" {
xsiTypeAttr = attr.Value
}
}
d.Skip()
*s = Typemap{Name: nameAttr, Type: typeAttr, XsiType: xsiTypeAttr}
return nil
}
- 1 回答
- 0 關(guān)注
- 261 瀏覽
添加回答
舉報