douwei9759 2019-08-31 01: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-31 02: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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?