dongluyi5123 2015-10-13 20:42
浏览 54
已采纳

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

I would like to parse xml using golang. Being new to using go, I've read articles around the web, explaining how to parse XML but I'm not sure why my return value is nil in this case.

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条回答 默认 最新

  • douya1855 2015-10-13 20:54
    关注

    I put the debugging feedback in a comment but I've just modified your example to work and it can be tested here; 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)
    }
    

    Here's a rundown of the four changes I made;

    1) print the Books object instead of the err returned from Unmarshal

    2) uppercase the first letter of fields on Book to make them 'exported' so they can be get/set by other packages (the unmarshaller in this case)

    3) add xml attributes. In exporting the fields it makes it so there isn't an implicit string match so you gotta explicitly specify which xml value is read into each field

    4) update the XML path for BookList for this you said it would be Books>Book but that implies another level of nesting that didn't exist in your xml. This object is Books, the elements you want in that list would have a relative xpath of simply Book so that's what you put there.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵