2 回答

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個贊
像其他所有屬性一樣獲取它:
type App struct {
XS string `xml:"xs,attr"`
}
游樂場:http : //play.golang.org/p/2IOmkX1Jov。
如果你也有一個實(shí)際的xs屬性 sans ,那就更棘手了xmlns。即使您將命名空間 URI 添加到XS的標(biāo)記,您也可能會收到錯誤消息。
編輯:如果你想獲得所有聲明的命名空間,你可以UnmarshalXML在你的元素上定義一個自定義并掃描它的屬性:
type App struct {
Namespaces map[string]string
Foo int `xml:"foo"`
}
func (a *App) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
a.Namespaces = map[string]string{}
for _, attr := range start.Attr {
if attr.Name.Space == "xmlns" {
a.Namespaces[attr.Name.Local] = attr.Value
}
}
// Go on with unmarshalling.
type app App
aa := (*app)(a)
return d.DecodeElement(aa, &start)
}
游樂場:http : //play.golang.org/p/u4RJBG3_jW。

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超3個贊
目前(Go 1.5),這似乎是不可能的。
我找到的唯一解決方案是使用倒帶元素:
func NewDocument(r io.ReadSeeker) (*Document, error) {
decoder := xml.NewDecoder(r)
// Retrieve xml namespace first
rootToken, err := decoder.Token()
if err != nil {
return nil, err
}
var xmlSchemaNamespace string
switch element := rootToken.(type) {
case xml.StartElement:
for _, attr := range element.Attr {
if attr.Value == xsd.XMLSchemaURI {
xmlSchemaNamespace = attr.Name.Local
break
}
}
}
/* Process name space */
// Rewind
r.Seek(0, 0)
// Standart unmarshall
decoder = xml.NewDecoder(r)
err = decoder.Decode(&w)
/* ... */
}
- 2 回答
- 0 關(guān)注
- 295 瀏覽
添加回答
舉報(bào)