猿问

使用 Unmarshal 在 Go 中获取 XML 命名空间前缀

我想知道是否可以使用 .xml 中的Unmarshal方法获取 XML 命名空间前缀 encoding/xml

例如,我有:

<application xmlns="http://wadl.dev.java.net/2009/02" xmlns:xs=" 
</application>

我想知道如何检索xs定义 XMLSchema 的前缀,而不必使用该Token方法。


元芳怎么了
浏览 255回答 2
2回答

哆啦的时光机

像其他所有属性一样获取它:type App struct {&nbsp; &nbsp; XS string `xml:"xs,attr"`}游乐场:http : //play.golang.org/p/2IOmkX1Jov。如果你也有一个实际的xs属性 sans ,那就更棘手了xmlns。即使您将命名空间 URI 添加到XS的标记,您也可能会收到错误消息。编辑:如果你想获得所有声明的命名空间,你可以UnmarshalXML在你的元素上定义一个自定义并扫描它的属性:type App struct {&nbsp; &nbsp; Namespaces map[string]string&nbsp; &nbsp; Foo&nbsp; &nbsp; &nbsp; &nbsp; int `xml:"foo"`}func (a *App) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {&nbsp; &nbsp; a.Namespaces = map[string]string{}&nbsp; &nbsp; for _, attr := range start.Attr {&nbsp; &nbsp; &nbsp; &nbsp; if attr.Name.Space == "xmlns" {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a.Namespaces[attr.Name.Local] = attr.Value&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; // Go on with unmarshalling.&nbsp; &nbsp; type app App&nbsp; &nbsp; aa := (*app)(a)&nbsp; &nbsp; return d.DecodeElement(aa, &start)}游乐场:http : //play.golang.org/p/u4RJBG3_jW。

皈依舞

目前(Go 1.5),这似乎是不可能的。我找到的唯一解决方案是使用倒带元素:func NewDocument(r io.ReadSeeker) (*Document, error) {&nbsp; &nbsp; decoder := xml.NewDecoder(r)&nbsp; &nbsp; // Retrieve xml namespace first&nbsp; &nbsp; rootToken, err := decoder.Token()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; }&nbsp; &nbsp; var xmlSchemaNamespace string&nbsp; &nbsp; switch element := rootToken.(type) {&nbsp; &nbsp; case xml.StartElement:&nbsp; &nbsp; &nbsp; &nbsp; for _, attr := range element.Attr {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if attr.Value == xsd.XMLSchemaURI {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; xmlSchemaNamespace = attr.Name.Local&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; /* Process name space */&nbsp; &nbsp; // Rewind&nbsp; &nbsp; r.Seek(0, 0)&nbsp; &nbsp; // Standart unmarshall&nbsp; &nbsp; decoder = xml.NewDecoder(r)&nbsp; &nbsp; err = decoder.Decode(&w)&nbsp; &nbsp; /* ... */}
随时随地看视频慕课网APP

相关分类

Go
我要回答