2016-05-06 71 views
0

你好StackOverFLowers!高昂:提取XML問題

我試圖從下面的XML ..... enter image description here

代碼:

package main 

import (
    "fmt" 
    "encoding/xml" 
    "net/http" 
    "log" 
    "io/ioutil" 
    "encoding/json" 

) 

type reportType struct{ 
    Course xml.CharData  `xml:"course"` 
    Crn xml.CharData `xml:"crn"` 
    Id xml.CharData `xml:"course>id"` 
    Section xml.CharData `xml:"course>section` 
    Title xml.CharData `xml:"course>title` 


} 
type myErrorType struct{ 
    TypeOfError xml.CharData `xml:"type"` 
    Desciption xml.CharData `xml:"description"` 
} 
type reportTypeJson struct{ 
    Course string  `json:"course"` 
    Crn string `json:"crn"` 
    Id string `json:"id"` 
    Section string `json:"section` 
    Title string `json:"title` 
    course map[string]string `json:"course"`; 
} 
func main() { 

    baseURL := "http://turing.cs.missouriwestern.edu/classes/csc346/final/?crn=13398"; 


    var query string 

    query = baseURL 
    fmt.Println("The escaped query: "+query) 

    response, err := http.Get(query) 
    doErr(err, "After the GET") 
    var body []byte 
    body, err = ioutil.ReadAll(response.Body) 
    fmt.Println(body); 
    doErr(err, "After Readall") 

    stringOfBody := string(body[:500]) 
    fmt.Printf("TASK 1: The body(as text): %s\n",stringOfBody) 

    //Unmarshalling 
    var report reportType 
    xml.Unmarshal(body, &report) 
    fmt.Printf("The Report: %s\n", report) 

    //Now marshal the data out in JSON 
    var data []byte 
    var output reportTypeJson 
    output.Course=string(report.Course) 
    output.Crn=string(report.Crn) 
    output.Id=string(report.Id) 
    output.Section=string(report.Section) 
    output.Title=string(report.Title) 

    //var output reportType 
    //output.Version = string(report.Version); 
    //report.Version -> output.Version 
    //output.TermsOfService = string(report.TermsOfService) 
    data,err = json.MarshalIndent(output,"","  ") 
    doErr(err, "From marshalIndent") 
    fmt.Printf("JSON output nicely formatted: \n%s\n",data) 

    fmt.Println("CRN: %v\n",report.Crn) 
    fmt.Println("ID: %v\n",report.Id) 
    fmt.Println("Section: %v\n",report.Section) 
    fmt.Println("Title: %v\n",report.Title) 
    fmt.Println("Course: %v\n",report.Course) 
    fmt.Println("ID: %v\n",report.Id) 


} 
func doErr(err error, message string){ 
    if err != nil{ 
     log.Panicf("ERROR: %s %s \n", message, err.Error()) 
    } 


} 

出於某種原因,它不是從文件給我提取數據基本上是空白報告。我在兩天前製作了一個類似這樣的程序,並遵循相同的格式,但我無法弄清楚我要去哪裏錯了。

OUTPUT:

The Report: { } 
JSON output nicely formatted: 
{ 
     "course": "", 
     "crn": "", 
     "id": "", 
     "Section": "", 
     "Title": "" 
} 

任何和所有幫助非常感謝,我有幾個小時的測試,我那時希望一些指導!謝謝!

回答

0

更改您在reportType上的xml屬性以刪除根元素:xml:"course>crn"應該是xml:"crn"。如果您不需要使用CharData,我還會將數據類型簡化爲字符串,以便稍後不再轉換它們。查看我的示例遊樂場,查看一個實例。

https://play.golang.org/p/xysSV-7oCA