Reputation: 4465
I would like to know if it is possible to get the XML namespace prefix using the
Unmarshal
method in encoding/xml
.
For example, I have:
<application xmlns="http://wadl.dev.java.net/2009/02" xmlns:xs="http://www.w3.org/2001/XMLSchema">
</application>
I would like to know how to retrieve the xs
defining the prefix for XMLSchema, without having to use the Token
method.
Upvotes: 2
Views: 4954
Reputation: 4465
Currently (Go 1.5), it does not seems to be possible.
The only solution I found, was to use rewind the element:
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)
/* ... */
}
Upvotes: 0
Reputation: 36249
Just get it like every other attribute:
type App struct {
XS string `xml:"xs,attr"`
}
Playground: http://play.golang.org/p/2IOmkX1Jov.
It gets trickier if you also have an actual xs
attribute, sans xmlns
. Even if you add the namespace URI to XS
's tag, you will probably get an error.
EDIT: If you want to get all declared namespaces, you can define a custom UnmarshalXML
on your element and scan it's attributes:
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)
}
Playground: http://play.golang.org/p/u4RJBG3_jW.
Upvotes: 3