GOLang:提取XML问题

时间:2016-05-06 16:30:46

标签: jquery json xml go extract

你好StackOverFLowers!

我试图从以下内容中提取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())
    }


}

由于某些原因,它没有从文件中提取数据,基本上是一个空白报告。我两天前做了一个类似这样的程序,并遵循相同的格式,但我无法弄清楚我哪里出错了。

输出:

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

非常感谢任何和所有的帮助,我在几个小时内接受了测试,我希望能够获得一些指导!谢谢!

1 个答案:

答案 0 :(得分:0)

更改reportType上的xml属性以删除根元素:xml:"course>crn"应为xml:"crn"。如果您不需要使用CharData,我也会将您的数据类型简化为字符串,这样您以后就不会对它们进行转换。有关工作示例,请参阅我的示例操场。

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