0

我正在编写一个程序,它可以读取完整的 MusicXML 文件,对其进行编辑,然后写出一个新文件。我正在使用 xml.Decode 将数据读入 MusicXML 文件的结构中,但是当我运行它时似乎什么也没发生。我尝试将 Decode 对象打印到屏幕上,但它打印了一个充满字节的结构。

我查看了 xml 包页面,似乎找不到任何涉及解码功能的线程。我根据我找到的一些指针尝试使用 UnMarshall,但这不起作用(这些线程中的大多数都较旧,所以自从 Decode 实施以来,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"`
}

我非常感谢任何见解。

4

1 回答 1

1

I think you've misunderstood the behavior of the decoder: it decodes XML into the object you pass to Decode:

song := xml.NewDecoder(io.Reader(f))
score := Score{}
err = song.Decode(&score)
// Decoded document is in score, *NOT* in song
return score

You're treating the decoder as if it will contain your document, but it's just a decoder. It decodes. To make it clearer in code, it should not be named song - it should be named, say, decoder or scoreDecoder or what have you. You almost certainly don't want to return an *xml.Decoder* from your function, but rather the decoded Score.

于 2017-09-13T17:26:18.120 回答