在Go中解析XML时处理命名空间 [英] Dealing with namespaces while parsing XML in Go

查看:88
本文介绍了在Go中解析XML时处理命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 包主要

导入(
encoding / xml
fmt


类型XML结构{
Foo字符串`xml:foo`


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












$ b xml.Unmarshal(rawXML, x)
fmt.Printf(foo:%s \ n,x.Foo)
}

此输出:

  foo:B 

虽然我预计它会产生:

  foo: A 

如何获取第一个 foo 标记(即一个没有命名空间)?

解决方案

我不认为XML解码器可以指定一个元素应该没有带有结构标签的名称空间。但是我知道它可以为您检索有关命名空间的信息,然后您可以在处理完数据后得到相同的结果:

  b 








$ b $ f $ struct $ {
XMLName xml.Name
数据字符串`xml:,chardata`
}

类型XML结构{
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 {
如果el.XMLName.Space =={
fmt.Printf(non namespaced foo%q,el.Data)
}
}
}

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


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\n", 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)?

解决方案

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\n", x)
    for _, el := range x.Foo {
       if el.XMLName.Space == "" {
          fmt.Printf("non namespaced foo %q", el.Data)
      }
    }
}

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

这篇关于在Go中解析XML时处理命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆