我正在写一个程序,可以读入一个完整的MusicXML文件,编辑它,并写出一个新的文件。我使用xml.Decode将数据读取到MusicXML文件的结构中,但是当我运行它时似乎没有发生任何事情。我尝试将Decode对象打印到屏幕上,但它打印了一个充满字节的结构。
我浏览了xml包页面,但似乎找不到任何涉及Decode函数的线程。我试着根据我找到的一些指针来使用UnMarshall,但不起作用(这些线程中的大多数都比较老,所以自从实现了UnMarshall以来,可能会有一些不同?)。
下面是输入函数:
func ImportXML(infile string) *xml.Decoder {
// Reads music xml file to memory
f, err := os.Open(infile)
if err != nil {
fmt.Fprintf(os.Stderr, "Error opening music xml file: %v\n", err)
os.Exit(1)
}
defer f.Close()
fmt.Println("\n\tReading musicXML file...")
song := xml.NewDecoder(io.Reader(f))
// must pass an interface pointer to Decode
err = song.Decode(&Score{})
if err != nil {
fmt.Fprintf(os.Stderr, "Error assigning musicXML file to struct: %v\n", err)
os.Exit(1)
}
return song
}下面是前几个结构(其余的遵循相同的格式):
type Score struct {
Work Work `xml:"work"`
Identification Identification `xml:"identification"`
Defaults Defaults `xml:"defaults"`
Credit Credit `xml:"credit"`
Partlist []Scorepart `xml:"score-part"`
Part []Part `xml:"part"`
}
// Name and other idenfication
type Work struct {
Number string `xml:"work-number"`
Title string `xml:"work-title"`
}
type Identification struct {
Type string `xml:"type,attr"`
Creator string `xml:"creator"`
Software string `xml:"software"`
Date string `xml:"encoding-date"`
Supports []Supports `xml:"supports"`
Source string `xml:"source"`
}我非常感谢你的见解。
发布于 2017-09-14 01:26:18
我认为您误解了解码器的行为:它将XML解码成您传递给Decode的对象。
song := xml.NewDecoder(io.Reader(f))
score := Score{}
err = song.Decode(&score)
// Decoded document is in score, *NOT* in song
return score您将解码器视为包含您的文档,但它只是一个解码器。它能解码。为了让它在代码中更清晰,它不应该被命名为song -它应该被命名为,比如说,decoder或scoreDecoder或其他什么。几乎可以肯定的是,您不希望从函数中返回*xml.Decoder*,而是希望返回已解码的Score。
https://stackoverflow.com/questions/46203443
复制相似问题