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 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 YOLOv8obb获取边框坐标时报错AttributeError: 'NoneType' object has no attribute 'xywhr'
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?