知识点掌握了,还需要不断练习才能熟练运用。下面编程网给大家带来一个Golang开发实战,手把手教大家学习《将 XML 文件转换为 CSV》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!
问题内容我正在尝试将 xml 文件解析为 csv。我的代码正在运行,没有出现任何错误,但结果为空。我无法弄清楚缺少什么部分。看起来 xml.unmarshal() 无法正常工作。
package domain
type row struct {
id string `xml:"id"`
posttypeid string `xml:"posttypeid"`
acceptedanswerid string `xml:"acceptedanswerid"`
creationdate string `xml:"creationdate"`
score string `xml:"score"`
viewcount string `xml:"viewcount"`
body string `xml:"body"`
owneruserid string `xml:"owneruserid"`
lasteditoruserid string `xml:"lasteditoruserid"`
lasteditordisplayname string `xml:"lasteditordisplayname"`
lasteditdate string `xml:"lasteditdate"`
lastactivitydate string `xml:"lastactivitydate"`
title string `xml:"title"`
tags string `xml:"tags"`
answercount string `xml:"answercount"`
commentcount string `xml:"commentcount"`
favoritecount string `xml:"favoritecount"`
communityowneddate string `xml:"communityowneddate"`
}
type posts struct {
posts []row `xml:"row"`
}
package main
import (
"encoding/csv"
"encoding/xml"
"fmt"
"go-mod/xml-csv/domain"
"io/ioutil"
"log"
"os"
)
func main() {
fmt.println("start converting.....")
xmlfile,err:=os.open("posts1.xml")
if err!=nil{
log.fatalf("error opening xml file fails:%s",err.error())
}
defer func() {
err=xmlfile.close()
if err!=nil{
log.printf("error closing file:%s",err.error())
}
}()
b,err := ioutil.readall(xmlfile)
if err !=nil{
log.fatalf("error reading file:%s",err.error())
}
//fmt.println(string(b))
var doc domain.posts
err2:=xml.unmarshal(b,&doc)
if err2!=nil{
fmt.println("errrrrrrr")
//log.fatalf("error unmarshaling to struct")
}
//fmt.println(doc)
file,err:=os.create("result.csv")
if err!=nil{
log.fatalf("error creating csv file:%s",err.error())
}
defer func() {
err=file.close()
if err!=nil{
log.print("error closing csv file")
}
}()
writer := csv.newwriter(file)
defer writer.flush()
for _,result:=range doc.posts{
//fmt.println(result)
err:=writer.write([]string{
result.id,
result.acceptedanswerid,
result.creationdate,
result.score,
result.viewcount,
result.body,
result.owneruserid,
result.lasteditoruserid,
result.lasteditordisplayname,
result.lasteditdate,
result.lastactivitydate,
result.title,
result.tags,
result.answercount,
result.commentcount,
result.favoritecount,
result.communityowneddate,
})
if err!=nil{
log.fatalf("error writing row to file:%s",err.error())
}
}
}
为了更好地理解,我在下面放了一些我使用过的示例 xml 文档
<?xml version="1.0" encoding="utf-8"?>
<posts>
<row Id="4" PostTypeId="1" AcceptedAnswerId="7" CreationDate="2008-07-31T21:42:52.667" Score="604" ViewCount="39047" Body="p>
" OwnerUserId="8" LastEditorUserId="6786713" LastEditorDisplayName="Rich B" LastEditDate="2018-07-02T17:55:27.247" LastActivityDate="2019-01-17T13:39:48.937" Title="Convert Decimal to Double?" Tags="<c#><floating-point><type-conversion><double><decimal>" AnswerCount="13" CommentCount="2" FavoriteCount="46" CommunityOwnedDate="2012-10-31T16:42:47.213" />
<row Id="6" PostTypeId="1" AcceptedAnswerId="31" CreationDate="2008-07-31T22:08:08.620" Score="273" ViewCount="17307" Body="/ol>
" OwnerUserId="9" LastEditorUserId="63550" LastEditorDisplayName="Rich B" LastEditDate="2016-03-19T06:05:48.487" LastActivityDate="2018-12-15T03:57:18.220" Title="Percentage width child element" Tags="<html><css><css3><internet-explorer-7>" AnswerCount="6" CommentCount="0" FavoriteCount="11" />
</posts>
解决方案
您的 Row 结构与 xml 本身不匹配。您有 row
元素,其中包含属性,这意味着您需要
Id 字符串 `xml:"Id,attrs"`
而不是 Id 字符串 `xml:"Id"`
等等
理论要掌握,实操不能落!以上关于《将 XML 文件转换为 CSV》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注编程网公众号吧!