dongqiang1894 2013-01-03 19:33
浏览 53
已采纳

在Go中解析XML时处理名称空间

I am trying to parse a piece if XML in Go:

package main

import (
    "encoding/xml"
    "fmt"
)

type XML struct {
    Foo string `xml:"foo"`
}

func main() {
    rawXML := []byte(`
<xml>
  <foo>A</foo>
  <ns:foo>B</ns:foo>
</xml>`)

    x := new(XML)
    xml.Unmarshal(rawXML, x)
    fmt.Printf("foo: %s
", x.Foo)
}

This outputs:

foo: B

While I expected it to produce:

foo: A

How do I get content of the first foo tag (i.e. one without namespace)?

  • 写回答

2条回答 默认 最新

  • dsrnwngq411594 2013-01-04 07:18
    关注

    I don't think the xml decoder can specify an element should have no namespace with struct tags. But I do know that it can retrieve the information about the namespaces for you and you could then post process the data after to get the same result:

    package main
    
    import (
        "encoding/xml"
        "fmt"
    )
    
    type Foo struct {
        XMLName xml.Name
        Data string `xml:",chardata"`
    }
    
    type XML struct {
        Foo []Foo `xml:"foo"`
    }
    
    func main() {
        rawXML := []byte(`
    <xml>
      <foo>A</foo>
      <ns:foo>B</ns:foo>
    </xml>`)
    
        x := new(XML)
        xml.Unmarshal(rawXML, x)
        //fmt.Printf("foo: %#v
    ", x)
        for _, el := range x.Foo {
           if el.XMLName.Space == "" {
              fmt.Printf("non namespaced foo %q", el.Data)
          }
        }
    }
    

    http://play.golang.org/p/aDEFPmHPc0

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?