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

标签 xml go

我想知道是否可以使用以下方法获取 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/

相关文章:

java - 使用 XSLT 模板从一个 JAXB 对象转换为另一个 JAXB 对象

java - 无法使用 sqlite 数据库中的数据填充 ListView

xml - xsltproc 合并 xml 文件不起作用

go - 如何设置 Ginkgo 测试套件?

ios - 将 XML 文件中的链接加载到 UIWebView(SIGABRT 错误)

java - 如何使用 JavaScript 处理 Java 对象序列化?

go - 一个go代码程序后台运行失败

autocomplete - Revel 框架和 Go 代码补全

go - cgo如何在c中表示go类型?

windows - exec.command不在Windows(golang)上执行