This is a creation in Article, where the information may have evolved or changed.
XML has been called our program open in a data exchange and information transmission is an indispensable role, of course, any language for XML parsing support is indispensable, today we learn to learn the XML parsing go.
XML file to parse: Student.xml
XML file Contents:
<span style= "FONT-SIZE:14PX;" ><?xml version= "1.0" encoding= "Utf-8"? ><students version= "1" ><student> <studentname >xixi</studentName> <studentId>3100561007</studentId></student><student> <studentName>xiaoq</studentName> <studentId>3100263101</studentId></student> </students></span>
The XML file contains information such as Student entity information, XML version, XML name, and so on, all we need to do is to get this information through the GO program.
In the Go language we use XML parsing package as Encoding/xml, the Main method is
Func unmarshal (data []byte, v interface{}) error
introducing the Go standard library you need to use :
Import ("Encoding/xml" "FMT" "Io/ioutil" "OS")
Define our XML and memory-mapped structure to accept the data: (Note: The fields in the struct description information need to correspond to one by one in the XML, and are case-sensitive, otherwise error parsing)
Type Student struct {xmlname XML. Name ' xml: ' Student ' ' Studentname string ' xml: ' studentname ' ' StudentID string ' xml: ' StudentID ' '}type recurlystudents struct {xmlname XML. Name ' xml: ' Students ' ' Version string ' xml: ' version,attr ' ' stustruct []student ' xml: ' Student ' Description string ' xml: ', InnerXml '}
Load the XML file and read the file information into data:
<span style= "White-space:pre" ></span><pre style= "margin-top:0px; margin-bottom:0px; " ><span style= "color: #c0c0c0;" > </span>fmt. Println (<span style= "color: #008000;" > "------------xml</span><span style=" color: #c0c0c0; " > </span><span style= "color: #008000;" > Parsing-----------"</span>)
file,err: =os. Open ("Student.xml")
iferr!=nil{
FMT. Println ("OpenxmlfileError")
return
}
deferfile. Close ()
data,err: =ioutil. ReadAll (file)
iferr!=nil{
FMT. PRINTLN ("readfilestreamError")
return
}
Parse the XML file and output:
Stus: = Recurlystudents{}err = XML. Unmarshal (data, &stus) if err! = Nil {fmt. PRINTLN ("Format XML data Failed") return}fmt. Println ("Description:" + stus. Description) fmt. Printf ("xmlname:%v\n", Stus. XMLName) fmt. Println ("xmlversion:" + stus. Version) for index, stu: = Range stus. stustruct {fmt. Printf ("The%d student,name:%s\n", Index+1, Stu. Studentname) fmt. Printf ("The%d student,id:%s\n", Index+1, Stu. StudentID)}
Over