我想知道是否可以使用以下方法获取 XML 命名空间前缀
encoding/xml
中的 Unmarshal
方法。
例如,我有:
<application xmlns="http://wadl.dev.java.net/2009/02" xmlns:xs="http://www.w3.org/2001/XMLSchema">
</application>
我想知道如何检索定义 XMLSchema 前缀的 xs
,而无需使用 Token
方法。
最佳答案
像其他属性一样获取它:
type App struct {
XS string `xml:"xs,attr"`
}
Playground :http://play.golang.org/p/2IOmkX1Jov .
如果您还有一个实际的 xs
属性(无 xmlns
),事情会变得更加棘手。即使您将命名空间 URI 添加到 XS
的标记中,您也可能会 get an error .
编辑:如果您想获取所有声明的命名空间,您可以在元素上定义自定义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)
}
Playground :http://play.golang.org/p/u4RJBG3_jW .
关于xml - 使用 Unmarshal 在 Go 中获取 XML 命名空间前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35044019/