2017-08-03 29 views
0

以下是我試圖將其引入Golang的一些XML文件。實際的XML文件超過500 MB。嘗試解組嵌套的XML時抓取所有字段

<artists> 
    <artist> 
     <id>1</id> 
     <name>The Persuader</name> 
     <realname>Jesper Dahlbäck</realname> 
     <profile /> 
    </artist> 
    <artist> 
     <id>22</id> 
     <name>DATacide</name> 
     <profile>Datacide began recording together in 1993, after Tetsu Inoue met Uwe Schmidt while vacationing near Frankfurt. 
     </profile> 
     <members> 
      <id>25</id> 
      <name>Tetsu Inoue</name> 
      <id>519207</id> 
      <name>Uwe Schmidt</name> 
     </members> 
    </artist> 
</artists> 

以下是Go代碼。我想要獲取MEMBERS部分中的所有ID字段,但我的代碼只抓取可能沒有,一個或多個ID的最後一個ID字段。我如何將MEMBERS部分中的所有ID都抓到MEMBERS數組中?

package main 

import (
    "encoding/xml" 
    "fmt" 
    "io/ioutil" 
    "os" 
) 

type Artists struct { 
    XMLName xml.Name `xml:"artists"` 
    Artist []Artist `xml:"artist"` 
} 

type Artist struct { 
    XMLName xml.Name `xml:"artist"` 
    ArtistID uint32 `xml:" id,omitempty"` 
    ArtistName string `xml:" name,omitempty"` 
    Profile string `xml:" profile,omitempty"` 
    RealName string `xml:" realname,omitempty"` 
    Members MembersID `xml:"members,omitempty"` 
} 

type MembersID struct { 
    MemberID uint32 `xml:"id,omitempty"` 
} 

func main() { 

    xmlFile, err := os.Open("short_artists.xml") 
    if err != nil { 
     fmt.Println(err) 
    } 

    fmt.Println("Successfully opened artists file") 
    defer xmlFile.Close() 

    byteValue, _ := ioutil.ReadAll(xmlFile) 
    var artists Artists 
    xml.Unmarshal(byteValue, &artists) 

    for i := 0; i < len(artists.Artist); i++ { 
     fmt.Println("ArtistID: " + fmt.Sprint(artists.Artist[i].ArtistID)) 
     fmt.Println("Name: " + artists.Artist[i].ArtistName) 
     fmt.Println("Real Name: " + artists.Artist[i].RealName) 
     fmt.Println("Profile: " + artists.Artist[i].Profile) 
     fmt.Println("") 
     fmt.Printf("%v\n",artists.Artist[i].Members) 
     fmt.Println("") 
    } 
} 

我所有的Google和DuckDuckGo搜索都是紫色的。感謝您的幫助。

+0

jeevatkm有正確的解決方案,但我想在另一注折騰 - 如果你」重新讀取500MB XML文件時,您可能會考慮使用['xml.Decoder'](https://golang.org/pkg/encoding/xml/#Decoder)進行流式解碼,而不是將整個500MB文件讀入內存,然後解碼它。 – Adrian

回答

1

問題是MembersID結構定義。你必須使用切片。

type MembersID struct { 
    MemberID []uint32 `xml:"id,omitempty"` 
} 

播放鏈接:https://play.golang.org/p/h4qTmSQoRg

輸出:

ArtistID: 1 
Name: The Persuader 
Real Name: Jesper Dahlbäck 
Profile: 

Members: [] 

ArtistID: 22 
Name: DATacide 
Real Name: 
Profile: Datacide began recording together in 1993, after Tetsu Inoue met Uwe Schmidt while vacationing near Frankfurt. 


Members: [25 519207] 

獎金提示:

選擇性讀取XML路徑值,如果需要的話。例如獲取XML路徑的所有ID artist>members>id

type MemberID struct { 
    IDs []uint32 `xml:"artist>members>id"` 
} 

播放鏈接:https://play.golang.org/p/sj7XPisgl7

輸出:

[25 519207] 
+0

我知道我不得不錯過那樣簡單的事情。謝謝你的答案。 – ericbrow

+0

@ericbrow不客氣。你可以接受答案。 – jeevatkm

相關問題