今天看了看XML的解析,挺别致的和C++,Java之类的解析很是不同。
GO中将XMl的结构解析成一个数据结构,类似于一个结构体。
package main import ( "encoding/xml" "fmt" "os" ) type Address struct { City,State string } type Person struct { XMLName xml.Name `xml:"person"` Id int `xml:"id,attr"` FirstName string `xml:"name>first"` LastName string `xml:"name>last"` Age int `xml:"age"` Height float32 `xml:"height,omitempty"` Married bool Address Comment string `xml:",comment"` } func main() { v := &Person{Id: 13,FirstName: "John",LastName: "Doe",Age: 42,Height: 172,Comment: " Need more details. "} v.Address = Address{"Hanga Roa","Easter Island"} output,err := xml.MarshalIndent(v," "," ") if err != nil { fmt.Printf("error: %v\n",err) } os.Stdout.Write(output) }
- the XMLName field,described above,is omitted. - a field with tag "-" is omitted. - a field with tag "name,attr" becomes an attribute with the given name in the XML element. - a field with tag ",attr" becomes an attribute with the field name in the XML element. - a field with tag ",chardata" is written as character data,not as an XML element. - a field with tag ",innerxml" is written verbatim,not subject to the usual marshalling procedure. - a field with tag ",comment" is written as an XML comment,not subject to the usual marshalling procedure. It must not contain the "--" string within it. - a field with a tag including the "omitempty" option is omitted if the field value is empty. The empty values are false,any nil pointer or interface value,and any array,slice,map,or string of length zero. - an anonymous struct field is handled as if the fields of its value were part of the outer struct.
上面是关于 那个结构的构成。
下面的两个例子 是读取xml的
<person id="13"> <name> <first>John</first> <last>Doe</last> </name> <age>42</age> <height>172</height> <Married>false</Married> <City>Hanga Roa</City> <State>Easter Island</State> <!-- Need more details. --> </person>代码1:
package main import ( "encoding/xml" "fmt" //"io" "os" ) type Address struct { City,comment"` } func main() { file,_ := os.Open("a.xml") fileinfo,_ := file.Stat() filesize := fileinfo.Size() buffer := make([]byte,filesize) file.Read(buffer) fmt.Printf("%s",buffer) person := Person{} xml.Unmarshal(buffer,&person) fmt.Println(person) fmt.Println(person.FirstName) fmt.Println(person.Age) fmt.Println(person.City) fmt.Println(person.LastName) }
代码2:
package main import ( "encoding/xml" "fmt" //"io" "os" ) type Address struct { City,State string } type Person struct { XMLName xml.Name `xml:"person"` Id int `xml:"id,attr"` FirstName string `xml:"name>first"` LastName string `xml:"name>last"` Age int `xml:"age"` Height float32 `xml:"height,omitempty"` Married bool Address Comment string `xml:",comment"` } func main() { file,_ := os.Open("a.xml") person := Person{} decoder := xml.NewDecoder(file) decoder.Decode(&person) fmt.Println(person) }
输出:
{{ person} 13 John Doe 42 172 false {Hanga Roa Easter Island} Need more details. }