英文:
Reading XML with golang
问题
我正在尝试使用Go语言读取XML。我基于这个示例进行开发,该示例是有效的。https://gist.github.com/kwmt/6135123#file-parsetvdb-go
这是我的文件:
Castle0.xml
<?xml version="1.0" encoding="UTF-8"?>
<Channel>
<Title>test</Title>
<Description>this is a test</Description>
</Channel>
test.go
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
type Query struct {
Chan Channel `xml:"Channel"`
}
type Channel struct {
title string `xml:"Title"`
desc string `xml:"Description"`
}
func (s Channel) String() string {
return fmt.Sprintf("%s - %d", s.title, s.desc)
}
func main() {
xmlFile, err := os.Open("Castle0.xml")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer xmlFile.Close()
b, _ := ioutil.ReadAll(xmlFile)
var q Query
xml.Unmarshal(b, &q)
fmt.Println(q.Chan)
}
输出:
- %!d(string=)
有人知道我做错了什么吗?(我正在学习Go,所以请对我宽容一些 :P)
英文:
I'm trying to read som XML with golang. I'm basing it on this example which works. https://gist.github.com/kwmt/6135123#file-parsetvdb-go
This is my files:
Castle0.xml
<?xml version="1.0" encoding="UTF-8" ?>
<Channel>
<Title>test</Title>
<Description>this is a test</Description>
</Channel>
test.go
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
type Query struct {
Chan Channel `xml:"Channel"`
}
type Channel struct {
title string `xml:"Title"`
desc string `xml:"Description"`
}
func (s Channel) String() string {
return fmt.Sprintf("%s - %d", s.title, s.desc)
}
func main() {
xmlFile, err := os.Open("Castle0.xml")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer xmlFile.Close()
b, _ := ioutil.ReadAll(xmlFile)
var q Query
xml.Unmarshal(b, &q)
fmt.Println(q.Chan)
}
Output:
- %!d(string=)
Any one know what I'm doing wrong? (I'm doing this to learn go, so go easy on me :P)
答案1
得分: 4
其他包,包括encoding/json
和encoding/xml
,只能看到导出的数据。所以首先你的title
和desc
应该分别是Title
和Desc
。
其次,在打印字符串时,你在Sprintf
中使用了%d
(整数)格式。这就是为什么你得到了%!d(string=)
,它的意思是“它不是一个整数,它是一个字符串!”。
第三,在你的XML中没有查询,所以直接解组到q.Chan
中。
这是一个可工作的示例。http://play.golang.org/p/l0ImL2ID-j
英文:
Other packages, including encoding/json
and encoding/xml
can only see exported data. So firstly your title
and desc
should be Title
and Desc
correspondingly.
Secondly, you're using %d
(integer) format in Sprintf
when printing a string. That's why you're getting %!d(string=)
, which means "it's not an integer, it's a string!".
Thirdly, there is no query in your XML, so unmarshal directly into q.Chan
.
This is the working example. http://play.golang.org/p/l0ImL2ID-j
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论