微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用gokogiri(libxml2)使用命名空间解析xml?

我使用 github.com/moovweb/gokogiri来解析XML文档.以下在解析var b时工作,但是当我在var a(具有命名空间)上尝试相同时,我得不到输出.如何使用gokogiri解析具有命名空间的XML?

package main

import (
    "github.com/moovweb/gokogiri"
    "github.com/moovweb/gokogiri/xpath"
    "log"
)

func main() {
    log.SetFlags(log.Lshortfile)
    doc,_ := gokogiri.ParseXml([]byte(a))
    defer doc.Free()
    doc.SetNamespace("","http://example.com/this")
    x := xpath.Compile(".//NodeA/NodeB")
    groups,err := doc.Search(x)
    if err != nil {
        log.Println(err)
    }
    for i,group := range groups {
        log.Println(i,group)
    }
}

var a = `<?xml version="1.0" ?><NodeA xmlns="http://example.com/this"><NodeB>thisthat</NodeB></NodeA>`
var b = `<?xml version="1.0" ?><NodeA><NodeB>thisthat</NodeB></NodeA>`

编辑#1:
我也试过doc.RegisterNamespace但得到了

doc.RegisterNamespace undefined (type *xml.XmlDocument has no field or method RegisterNamespace)”

和x.RegisterNamespace获取

x.RegisterNamespace undefined (type *xpath.Expression has no field or method RegisterNamespace)”

解决方法

尽管XML中使用的命名空间没有分配前缀(即认值),但您需要注册一个并在xpath表达式中使用它.

这个前缀可以是你喜欢的任何东西,这里我使用ns.请注意,它可能与文档中使用的前缀(如果有)不同 – 需要匹配的重要部分是命名空间字符串本身.

例:

package main

import (
    "fmt"
    "github.com/moovweb/gokogiri"
    "github.com/moovweb/gokogiri/xpath"
)

func main() {
    doc,_ := gokogiri.ParseXml([]byte(a))
    defer doc.Free()
    xp := doc.DocXPathCtx()
    xp.RegisterNamespace("ns","http://example.com/this")
    x := xpath.Compile("/ns:NodeA/ns:NodeB")
    groups,err := doc.Search(x)
    if err != nil {
        fmt.Println(err)
    }
    for i,group := range groups {
        fmt.Println(i,group.Content())
    }
}

var a = `<?xml version="1.0" ?><NodeA xmlns="http://example.com/this"><NodeB>thisthat</NodeB></NodeA>`

输出

0 thisthat

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。