加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 22:41:30 所属栏目:百科 来源:网络整理
导读:我使用 github.com/moovweb/gokogiri 来解析XML文档.以下在解析var b时工作,但是当我在var a(具有命名空间)上尝试相同时,我得不到输出.如何使用gokogiri解析具有命名空间的XML? package mainimport ( "github.com/moovweb/gokogiri" "github.com/moovweb/go
我使用 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读