dongmu5106 2014-11-02 15:15
浏览 90
已采纳

使用Go解析XML,并以小写形式包含多个元素

I don't know how to make this code work. I'm just trying to parse a simple XML file like this:

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
", s)
    fmt.Println(s.Data)
}

what I got is:

{{ struct} []}
[]

But when I change the "data" elements to uppercase, like this:

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
", s)
    fmt.Println(s.Data)
}

I got this:

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

Can anybody tell me why?

  • 写回答

1条回答 默认 最新

  • dongxie8856 2014-11-02 15:21
    关注

    If you do not put XML annotation on the structure field the name of the field is taken as name of XML element.

    In the documentation on Unmarshal in endoding/xml package we can find the following:

    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.

    The matching is case sensitive so it makes a difference in your case.

    I recommend annotating the structure like this to fit the actual data:

    type Struct struct {
        XMLName xml.Name `xml:"struct"`
        Data    []Data   `xml:"data"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算