xml - 使用 Go 解析 XML,具有多个小写元素

标签 xml go

我不知道如何使这段代码工作。我只是想像这样解析一个简单的 XML 文件:

package main

import (
    "encoding/xml"
    "fmt"
)

type Data struct {
    XMLName xml.Name `xml:"data"`
    Nam     string   `xml:"nam,attr"`
}

type Struct struct {
    XMLName xml.Name `xml:"struct"`
    Data    []Data
}

func main() {

    x := `  
        <struct>
            <data nam="MESSAGE_TYPE">     
            </data>
            <data nam="MESSAGE_TYPE2">
            </data>
        </struct>
    `
    s := Struct{}
    err := xml.Unmarshal([]byte(x), &s)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%v\n", s)
    fmt.Println(s.Data)
}

我得到的是:

{{ struct} []}
[]

但是当我将“数据”元素更改为大写时,如下所示:

package main

import (
    "encoding/xml"
    "fmt"
)

type Data struct {
    XMLName xml.Name `xml:"Data"`
    Nam     string   `xml:"nam,attr"`
}

type Struct struct {
    XMLName xml.Name `xml:"struct"`
    Data    []Data
}

func main() {

    x := `  
        <struct>
            <Data nam="MESSAGE_TYPE">     
            </Data>
            <Data nam="MESSAGE_TYPE2">
            </Data>
        </struct>
    `
    s := Struct{}
    err := xml.Unmarshal([]byte(x), &s)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%v\n", s)
    fmt.Println(s.Data)
}

我明白了:

{{ struct} [{{ Data} MESSAGE_TYPE} {{ Data} MESSAGE_TYPE2}]}
[{{ Data} MESSAGE_TYPE} {{ Data} MESSAGE_TYPE2}]

谁能告诉我为什么?

最佳答案

如果您没有在结构字段上放置 XML 注释,则该字段的名称将作为 XML 元素的名称。

Unmarshal 上的文档中在 endoding/xml 包中,我们可以找到以下内容:

Unmarshal maps an XML element to a struct using the following rules. In the rules, the tag of a field refers to the value associated with the key 'xml' in the struct field's tag (see the example above).

  • If the XML element contains a sub-element whose name matches a field without any mode flags (",attr", ",chardata", etc), Unmarshal maps the sub-element to that struct field.

匹配区分大小写,因此它会影响您的大小写。

我建议像这样注释结构以适合实际数据:

type Struct struct {
    XMLName xml.Name `xml:"struct"`
    Data    []Data   `xml:"data"`
}

关于xml - 使用 Go 解析 XML,具有多个小写元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26700825/

相关文章:

go - 无法使用 net.Conn.Read 从 UNIX 套接字读取

linux - 不能在基于 linux-amd64 构建的 darwin-amd64 二进制文件中使用 https

xml - 使用 Xpath 比较两个 xml 字段

python - 使用Python从xml中的一个节点遍历到另一个节点

algorithm - Go 中的容器类型

go - 高并发下Go `net/http`的一些困惑

go - 从包函数返回 Mock

java - 为什么schtasks无法识别XML语法?

xml - XPATH 未显示任何数据

html - 如何在 Perl 中将 HTML 转换为 RTF?