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

时间:2016-01-27 17:23:42

标签: xml go

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

例如,我有:

<application xmlns="http://wadl.dev.java.net/2009/02" xmlns:xs="http://www.w3.org/2001/XMLSchema">
</application>

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

2 个答案:

答案 0 :(得分:2)

就像其他所有属性一样:

type App struct {
    XS string `xml:"xs,attr"`
}

游乐场: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)
}

游乐场:http://play.golang.org/p/u4RJBG3_jW

答案 1 :(得分:0)

目前(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)

    /* ... */
}
相关问题