douwei9759 2019-08-30 17:55
浏览 60
已采纳

无法使用Go获取XML属性

I wrote the following code and XML file to try to reproduce the situation I am dealing with- I am able to retrieve every other tag's data except TEST, and I am not sure why. Any help is appreciated!

For example, in the below code I am able to get the data for the ST tag but not the TEST tag.

XML Code

<R>
<ST N="Hello" />
<JK M="Hello World">
<TEST NM="Got Test Tag" />
</JK>
</R>

Go code

package main

import (
    "encoding/xml"
    "fmt"
    "io"
    "os"
    "golang.org/x/text/encoding/charmap"
)

type test struct {
    XMLName xml.Name `xml:"R"`
    AllTest []testTest `xml:"TEST"`
    ST []testST `xml:"ST"`
}
type testST struct {
    XMLName xml.Name `xml:"ST"`
    STVal string `xml:"N,attr"`
}
type testTest struct {
    XMLName xml.Name `xml:"TEST"`
    testVal string `xml:"NM,attr"`
}

func makeCharsetReader(charset string, input io.Reader) (io.Reader, error) {
    if charset == "Windows-1252" {
        return charmap.Windows1252.NewDecoder().Reader(input), nil
    }
    return nil, fmt.Errorf("Unknown charset: %s", charset)
}

func parse(testPath string) {
    xmlFile, err := os.Open(testPath)
    if err != nil {
        panic(err)
    }
    defer xmlFile.Close()
    var parseDoc test
    decoder := xml.NewDecoder(xmlFile)
    decoder.CharsetReader = makeCharsetReader
    err = decoder.Decode(&parseDoc)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(parseDoc.AllTest)
    fmt.Println(parseDoc.ST)
}

func main() {
    filePath := "absolute_path_to_the_xml_file"
    parse(filePath)
}

The output I get is

[] [{{ ST} Hello}]

The output for the ST tag is as expected, but why do I get no data for the TEST tag?

展开全部

  • 写回答

1条回答 默认 最新

  • dongtuo3530 2019-08-30 18:15
    关注

    The TEST element in your example is a child of JK, but your struct definitions expect it to be a child of R. Try the struct definitions shown below.

    type test struct {
        XMLName xml.Name `xml:"R"`
        JK      JK       `xml:"JK"`
        ST      []testST `xml:"ST"`
    }
    
    type JK struct {
        AllTest []testTest `xml:"TEST"`
    }
    
    type testST struct {
        XMLName xml.Name `xml:"ST"`
        STVal   string   `xml:"N,attr"`
    }
    
    type testTest struct {
        XMLName xml.Name `xml:"TEST"`
        TestVal string   `xml:"NM,attr"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部