【问题标题】:Golang Decode MusicXMLGolang 解码 MusicXML
【发布时间】:2017-09-13 17:20:24
【问题描述】:

我正在编写一个程序,它可以读入一个完整的 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"`
}

我非常感谢任何见解。

【问题讨论】:

    标签: xml go musicxml


    【解决方案1】:

    我认为您误解了解码器的行为:它将 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

    【讨论】:

    • 你是绝对正确的。当然,它必须有如此明显的痛苦。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2019-03-12
    • 1970-01-01
    相关资源
    最近更新 更多