无法使用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?
答
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"`
}