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
         */     
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题