【问题标题】:go xml parsing "doesn't see" any fieldsgo xml解析“看不到”任何字段
【发布时间】:2013-09-30 18:37:01
【问题描述】:

我一定遗漏了一些非常明显的东西......我正在尝试解析一个简单的 XML 文件,按照此处 ExampleUnmarshal() 的示例:http://golang.org/src/pkg/encoding/xml/example_test.go

正如您将在底部看到的那样,没有任何属性或子元素被映射 - 无论是方向 - Marshal 还是 Unmarshal。据我所知,这与他们在上面的 example_test.go 中所做的几乎完全相同(我能看到的唯一区别是该测试中的类型在函数的范围内 - 我尝试过,没有差异,他们使用的是子元素而不是属性 - 除了id - 但根据doc 名称,attr 应该可以正常工作。

代码如下:

package main

import (
    "fmt"
    "encoding/xml"
    "io/ioutil"
)


type String struct {
    XMLName xml.Name `xml:"STRING"`
    lang  string   `xml:"lang,attr"`
    value  string   `xml:"value,attr"`
}

type Entry struct {
    XMLName xml.Name `xml:"ENTRY"`
    id      string  `xml:"id,attr"`
    strings []String 
}

type Dictionary struct {
    XMLName xml.Name `xml:"DICTIONARY"`
    thetype  string   `xml:"type,attr"`
    ignore  string   `xml:"ignore,attr"`
    entries []Entry  
}

func main() {

    dict := Dictionary{}

    b := []byte(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<DICTIONARY type="multilanguage" ignore="en">
  <ENTRY id="ActionText.Description.AI_ConfigureChainer">
    <STRING lang="en" value="ActionText.Description.AI_ConfigureChainer"/>
    <STRING lang="da" value=""/>
    <STRING lang="nl" value=""/>
    <STRING lang="fi" value=""/>
  </ENTRY>
</DICTIONARY>
`)

    err := xml.Unmarshal(b, &dict)
    if err != nil { panic(err) }

    fmt.Println(dict) // prints: {{ DICTIONARY}   []}

    dict.ignore = "test"

    out, err := xml.MarshalIndent(&dict, "  ", "    ")
    fmt.Println(string(out)) // prints:   <DICTIONARY></DICTIONARY>

    // huh?

}

【问题讨论】:

    标签: xml xml-parsing go


    【解决方案1】:

    您需要Export(大写)您的结构字段。

    来自encoding/xml Marshall 函数文档:

    结构的 XML 元素包含结构的每个导出字段的编组元素

    请参阅Unable to parse a complex json in golang 以获得相关答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-31
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-20
      相关资源
      最近更新 更多