dongxidui1227 2014-12-14 21:19
浏览 51
已采纳

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

I am using github.com/moovweb/gokogiri to parse an XML document. The following works when parsing var b but when I try the same on var a (which has a namespace) I get no output. How do I parse XML that has a namespace using gokogiri?

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>`

EDIT #1: I've also tried doc.RegisterNamespace but got

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

and x.RegisterNamespace getting

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

  • 写回答

1条回答 默认 最新

  • dongxing4196 2014-12-14 23:12
    关注

    Even though the namespace used in the XML is assigned no prefix (i.e. is default), you do need to register one and use it in your xpath expression.

    This prefix can be anything you like, here I used ns. Note it can be different from the prefix used in the document (if any) - the important part that needs to match is the namespace string itself.


    Example:

    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>`
    

    Output:

    0 thisthat
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题