从 zip 取消编组特定的 XML 文件而不提取



我有一个zip文件,其中包含几个xml文件,使用zip和Go archive中的编码/xml包。我想做的是a.xml解组为一个类型 - 即不循环访问其中的所有文件:

test.zip
├ a.xml
├ b.xml
└ ...

a.xml将具有如下结构:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <app>
        <code>0001</code>
        <name>Some Test App</name>
    </app>
    <app>
        <code>0002</code>
        <name>Another Test App</name>
    </app>
</root>

如何选择和取消封送名称作为参数在注释掉的行中提供的文件,例如:

package marshalutils
import (
    "archive/zip"
    "log"
    "fmt"
    "encoding/xml"
)
type ApplicationRoot struct {
    XMLName xml.Name `xml:"root"`
    Applications []Application `xml:"app"`
}
type Application struct {
    Code string `xml:"code"`
    Name string `xml:"name"`
}
func UnmarshalApps(zipPath string, fileName string) {
    // Open a zip archive for reading.
    reader, err := zip.OpenReader(zipFilePath)
    if err != nil {
        log.Fatal(`ERROR:`, err)
    }
    defer reader.Close()
    /* 
     * U N M A R S H A L   T H E   G I V E N   F I L E ...
     * ... I N T O   T H E   T Y P E S   A B O V E
     */
}

好吧,这是我在示例函数中添加返回类型声明时找到的答案:

func UnmarshalApps(zipPath string, fileName string) ApplicationRoot {
    // Open a zip archive for reading.
    reader, err := zip.OpenReader(zipFilePath)
    if err != nil {
        log.Fatal(`ERROR:`, err)
    }
    defer reader.Close()
    /* 
     * START OF ANSWER
     */
    var appRoot ApplicationRoot
    for _, file := range reader.File {
        // check if the file matches the name for application portfolio xml
        if file.Name == fileName {
            rc, err := file.Open()
            if err != nil {
                log.Fatal(`ERROR:`, err)
            }
            // Prepare buffer
            buf := new(bytes.Buffer)
            buf.ReadFrom(rc)
            // Unmarshal bytes
            xml.Unmarshal(buf.Bytes(), &appRoot)
            rc.Close()
        }
    }   
     /* 
     * END OF ANSWER
     */     
}

最新更新