我有一个 zip 文件,里面有几个 xml 文件,使用 zip和 encoding/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/