go XML processing

XML data format

For the following XML:

<Person>
    <FirstName>Laura</FirstName>
    <LastName>Lynn</LastName>
</Person>

And JSON the same manner, data can be serialized as XML structure, or structure from the XML data deserialized;

encoding / xml package implements a simple XML parser (SAX), is used to parse the XML data content. The following example shows how to use the parser:

Example  xml.go :

// xml.go
package main

import (
    "encoding/xml"
    "fmt"
    "strings"
)

var t, token xml.Token
var err error

func main() {
    input := "<Person><FirstName>Laura</FirstName><LastName>Lynn</LastName></Person>"
    inputReader := strings.NewReader(input)
    p := xml.NewDecoder(inputReader)

    for t, err = p.Token(); err == nil; t, err = p.Token() {
        switch token := t.(type) {
        case xml.StartElement:
            name := token.Name.Local
            fmt.Printf("Token name: %s\n", name)
            for _, attr := range token.Attr {
                attrName := attr.Name.Local
                attrValue := attr.Value
                fmt.Printf("An attribute is: %s %s\n", attrName, attrValue)
                // ...
            }
        case xml.EndElement:
            fmt.Println("End of token")
        case xml.CharData:
            content := string([]byte(token))
            fmt.Printf("This is the content: %v\n", content)
            // ...
        default:
            // ...
        }
    }
}

Output:

Token name: Person
Token name: FirstName
This is the content: Laura
End of token
Token name: LastName
This is the content: Lynn
End of token
End of token

Defines several package type XML tags: StartElement, Chardata (which is from the beginning to the end of the actual text of the label between the label), EndElement, Comment, Directive or ProcInst.

Packet parser also defines a structure: NewParser The method of holding an io.Reader a (where a particular type of strings.NewReader) and generates an object type of a parser. Another  Token() method returns the input stream in the next XML token. At the end of the input stream, it will return (nil, io.EOF)

XML text is processed until the loop  Token() returns an error, because the end of the file has been reached, no more content available to deal with. It can be further processed by a type-switch, according to some XML tags. Chardata content only in a [] byte, let it becomes readable by the string conversion stronger.

JSON data format

We are more familiar with XML format (see  12.10 ); but sometimes JSON (JavaScript Object Notation, see  http://json.org ) is used as the first choice, mainly because of the format is very simple. JSON is commonly used for communication between the web browser and the back-end, but is also useful in other scenes.

This is a short fragment :( JSON and XML synonymous above)

{
    "Person": {
        "FirstName": "Laura",
        "LastName": "Lynn"
    }
}

Although XML is widely used, but JSON is more compact, lightweight (take up less memory, disk and network bandwidth) and better readability, it also makes it more and more popular.

Example  json.go :

// json.go
package main

import (
    "encoding/json"
    "fmt"
    "log"
    "os"
)

type Address struct {
    Type    string
    City    string
    Country string
}

type VCard struct {
    FirstName string
    LastName  string
    Addresses []*Address
    Remark    string
}

func main() {
    pa := &Address{"private", "Aartselaar", "Belgium"}
    wa := &Address{"work", "Boom", "Belgium"
    U:}= VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"}
    // fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}:
    // JSON format:
    js, _ := json.Marshal(vc)
    fmt.Printf("JSON format: %s", js)
    // using an encoder:
    file, _ := os.OpenFile("vcard.json", os.O_CREATE|os.O_WRONLY, 0666)
    defer file.Close()
    enc := json.NewEncoder(file)
    err := enc.Encode(vc)
    if err != nil {
        log.Println("Error in encoding json")
    }
}

 

 

 

Reprinted from: https://github.com/unknwon/the-way-to-go_ZH_CN/blob/master/eBook/12.10.md

Guess you like

Origin www.cnblogs.com/lfri/p/11768826.html