xml - Golang 解码 MusicXML

标签 xml go musicxml

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

我查看了 xml 包页面,但似乎找不到任何涉及 Decode 函数的线程。我尝试根据我发现的一些指示使用 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"`
}

我非常感谢任何见解。

最佳答案

我认为您误解了解码器的行为:它将 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 - 它应该被命名为,比如说,decoderscoreDecoder 或者你有什么。您几乎肯定不想从函数返回 *xml.Decoder*,而是返回解码后的 Score

关于xml - Golang 解码 MusicXML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46203443/

相关文章:

java - TransformerFactory - 避免网络查找来验证 DTD

javascript - 如何复制整行?

go - 使用 Go 控制另一个窗口

regex - 在 golang 正则表达式中获取子组的命名列表

用于通过 RPC 传递匿名函数的 GobEncoder

python - 从 Musicxml 中提取信息

C# 到 MusicXML?

安卓工作室 : not rendering shapes. xml

xml - 从一个 xml 文件复制到另一个 - powershell

java - 在对话框打开时显示 toast ?