xml - 从 zip 中解码特定的 XML 文件而不提取

标签 xml go zip

我有一个 zip 文件,里面有几个 xml 文件,使用 zipencoding/xml来自 Go 存档的包。我想做的是将 only 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
     */     
}

关于xml - 从 zip 中解码特定的 XML 文件而不提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46691251/

相关文章:

python - 基于多个相邻值的 XPATH

python - 如何使用ElementTree在python中添加xml节点

git - Gocode工具错误

string - 使用 Go 截断 slice 的每个成员

c# - 如何在将文件对保持在一起的同时压缩具有最大输出大小的多个文件

Angular 4 下载 base64 图像数组作为 ZIP 文件

xml - 指定 XML 模式中元素列表的排序

xml - 将 LINQ 嵌套到 XML

没有IV的AES128

java - 在 zip 中的 xml 文件上使用 SAX 解析器