在Go中读取XML文件

I did a small code in Go, that I thought it was good enough to read an XML file.

Can someone know what is happing?

XML file:

<Lang>
    <Name> Go </Name>
    <Year> 2009 </Year>
    <URL> http://golang.org/ </URL>

</Lang>

Go code:

package main

import (
    "io"
    "log"
    "os"
)

func main() {
    input, err := os.Open("C:\GoWork\toy\lang.xml")
    if err != nil {
        log.Fatal(err)
    }
    io.Copy(os.Stdout, input)
}

Error message:

.\xmltoStruct.go:11: unknown escape sequence: G
.\xmltoStruct.go:11: unknown escape sequence: l

A string literal between double quotes is an interpreted string literal where backslash is a special character denoting escape sequences. See Spec: String literals:

The text between the quotes forms the value of the literal, with backslash escapes interpreted as they are in rune literals (except that \' is illegal and \" is legal), with the same restrictions.

Either double quote your backslashes:

input, err := os.Open("C:\\GoWork\\toy\\lang.xml")

Or easier: use a raw string literal (backticks) where backslash has no special meaning:

input, err := os.Open(`C:\GoWork\toy\lang.xml`)

Also you should close your file, preferably as a deferred statement:

input, err := os.Open(`C:\GoWork\toy\lang.xml`)
if err != nil {
    log.Fatal(err)
}
defer input.Close()
io.Copy(os.Stdout, input)

Currently this is mix of two literal forms

input, err := os.Open("C:\GoWork\toy\lang.xml")

There are basically two forms of string literals: a. raw string literals b. interpreted string literals

either use raw string literal with back quotes, as in `foo` and the value of literal has no special meaning between the quotes

or interpreted string literals with double quotes, as in "bar" but take precaution because the value are interpreted as in rune literals