在golang中解析xml字符串时<nil>

时间:2015-10-13 20:42:05

标签: xml go

我想使用xml解析golang。作为使用go的新手,我已经阅读了网络上的文章,解释了如何解析XML,但我不确定为什么在这种情况下我的返回值为nil

package main

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

func check(e error) {
    if e != nil {
        panic(e)
    }
}

type Books struct {
    XMLName xml.Name `xml:"Books"`
    BookList []Book `xml:"Books>Book"`
}

type Book struct {
    title string `xml:"title,attr"`
    author string
    published string
}

func main() {
    //f, err := ioutil.ReadFile("xml/Books.xml")
    //check(err)

    var data = []byte(`
        <Books>
            <Book title="A Brief History of Time" author="Stephen Hawking" published="1988">
                <title>title here</title>
                A Brief History of Time: From the Big Bang to Black Holes is a 1988 popular-science book by British physicist Stephen Hawking. It became a bestseller and sold more than 10 million copies in 20 years.
            </Book>
            <Book title="Steve Jobs" author="Walter Isaacson" published="2011">
                Steve Jobs is the authorized self-titled biography book of Steve Jobs. The book was written at the request of Jobs by Walter Isaacson, a former executive at CNN.
            </Book>
        </Books>
    `)

    b := Books{}
    o := xml.Unmarshal([]byte(data), &b)
    fmt.Println(o)
}

1 个答案:

答案 0 :(得分:2)

我把调试反馈放在评论中,但我刚刚修改了你的例子,可以在这里进行测试; https://play.golang.org/p/_UIph2je7f

package main

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

func check(e error) {
    if e != nil {
        panic(e)
    }
}

type Books struct {
    XMLName xml.Name `xml:"Books"`
    BookList []Book `xml:"Book"`
}

type Book struct {
    Title string `xml:"title,attr"`
    Author string `xml:"author,attr"`
    Published string `xml:"published,attr"`
}

func main() {
    //f, err := ioutil.ReadFile("xml/Books.xml")
    //check(err)

    var data = []byte(`
        <Books>
            <Book title="A Brief History of Time" author="Stephen Hawking" published="1988">
                <title>title here</title>
                A Brief History of Time: From the Big Bang to Black Holes is a 1988 popular-science book by British physicist Stephen Hawking. It became a bestseller and sold more than 10 million copies in 20 years.
            </Book>
            <Book title="Steve Jobs" author="Walter Isaacson" published="2011">
                Steve Jobs is the authorized self-titled biography book of Steve Jobs. The book was written at the request of Jobs by Walter Isaacson, a former executive at CNN.
            </Book>
        </Books>
    `)

    b := Books{}
    o := xml.Unmarshal([]byte(data), &b)
    fmt.Println(o)
    fmt.Println(b)
}

以下是我所做的四项修改的简要说明;

1)打印Books对象,而不是从Unmarshal

返回的错误

2)大写Book上的第一个字母以使它们'导出',以便它们可以被其他包(在这种情况下为unmarshaller)获取/设置

3)添加xml属性。在导出字段时,它使得它没有隐式字符串匹配,因此您必须明确指定将哪个xml值读入每个字段

4)为BookList更新Books的XML路径,你说它将是Books&gt; Book,但这意味着你的xml中不存在另一层嵌套。这个对象是Book,你在列表中想要的元素的相对xpath只有function updateHandler(callback) { var response; var targetUrl; // disabled the login button to avoid multiple events $("#btnLogin").prop('disabled', true); var loginData = { grant_type: 'password', NewPassword: $("#txtNewPassword").val(), OldPassword: $("#txtOldPassword").val(), ConfirmPassword: $("#txtConfirmPassword").val() }; var token = sessionStorage.getItem(tokenKey); var headers = {}; if (token) { headers.Authorization = 'Bearer ' + token; } targetUrl = "/api/account/ChangePassword"; $.ajax({ type: 'POST', url: targetUrl, data: loginData, headers: headers, }).done(function (data) { closeChangePassword(); }).fail(function (xhr, textStatus, errorThrown) { passwordErrorHandler(xhr,0); // re-enable the login button $("#btnLogin").prop('disabled', false); }); ,这就是你放在那里的东西。