zoukankan      html  css  js  c++  java
  • go语言学习之解析XML

     1
    <?xml version="1.0" encoding="UTF-8"?>
    <bookstore>
        <book>
            <name>11</name>
            <author>11</author>
            <year>2014</year>
            <price>89</price>
        </book>
        <book>
            <name>131</name>
            <author>131</author>
            <year>20314</year>
            <price>839</price>
        </book>    
    </bookstore>
    package main
     2 
     3 import (
     4        "encoding/xml"
     5 "fmt"
     6 "io/ioutil"
     7 "os"
     8    )
     9 
    10 type BookStore struct {  
    11     XMLName xml.Name  `xml:"bookstore"`
    12     Books []book  `xml:"book"`
    13     Description string `xml:",innerxml"`
    14 }
    15 
    16 type book struct {
    17     XMLName xml.Name `xml:"book"`
    18     Name string `xml:"name"`
    19 //    author string `xml:"author"`
    20 //    year string `xml:"year"`
    21 //    price string `xml:"price"`
    22 }
    23 
    24 func needPrintfErr(err error) bool {
    25     if err != nil {
    26         fmt.Printf("error: %v", err)
    27         return true
    28     }
    29     return false;
    30 }
    31 
    32 func main() {
    33     file, err := os.Open("/home/liq-n/eclipse-workspace/MyFirstGolang/src/main/bookInfo.xml")
    34     if needPrintfErr(err) {
    35     return
    36     }
    37     
    38     defer file.Close()
    39     data, err := ioutil.ReadAll(file)
    40     if needPrintfErr(err) {
    41     return
    42     }
    43     
    44     bookInfo := BookStore{}
    45     err = xml.Unmarshal(data, &bookInfo)
    46     if needPrintfErr(err){
    47     return 
    48     }
    49     fmt.Println(bookInfo)
    50 }
  • 相关阅读:
    跨浏览器的事件处理程序(javascript高级程序设计第二版第十二章)
    json
    html5 本地存储Web Storage
    sicily 6497. 字符统计
    sicily 6415. linear correlation
    sicily 1154. Easy sort
    sicily 6496. 二维数组
    sicily 6423. 反向输出数字
    sicily 1636. show me the money
    sicily 1324. Score
  • 原文地址:https://www.cnblogs.com/xzlq/p/14341469.html
Copyright © 2011-2022 走看看