我有一个zip文件,其中包含Go存档中的zip和encoding/xml个包中的几个xml文件。我想要做的是将仅 a.xml
解组为类型-i.e.没有循环遍历所有文件:
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
*/
}
答案 0 :(得分:0)
嗯,这是我在样本函数中添加返回类型声明时找到的答案:
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
*/
}