doudiecai1572 2017-10-11 14:46
浏览 38
已采纳

从zip解组特定的XML文件而不解压缩

I have a zip file having several xml files in it using zip and encoding/xml packages from Go archive. The thing I want to do is unmarshalling only a.xml into a type -i.e. without looping over all files inside:

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

a.xml would have a structure like:

<?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>

How to for select and unmarshal the file whose name is provided as a parameter in the commented out lines, for instance:

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
     */
}
  • 写回答

1条回答 默认 最新

  • dsg56465 2017-10-12 11:57
    关注

    Well, here is the answer I have found with the return type declaration added to the sample function:

    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
         */     
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号