前端之家收集整理的这篇文章主要介绍了
golang android xml parse,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main
import (
"encoding/xml"
"strings"
"fmt"
"log"
"os"
"io/IoUtil"
)
type Node struct {
XMLName xml.Name
Id string `xml:"http://schemas.android.com/apk/res/Android id,attr"`
Nodes []Node `xml:",any"`
}
func walk(n Node,isNodeFunc func(Node) bool,workWithNode func(Node,interface{}),data interface{}){
var cacheNodes []Node = make([]Node,0)
cacheNodes = append(cacheNodes,n)
for ;len(cacheNodes)>0; {
current_node := cacheNodes[0]
if isNodeFunc(current_node) {
workWithNode(current_node,data)
}
cacheNodes = cacheNodes[1:]
if(len(n.Nodes)>0){
cacheNodes = append(cacheNodes,current_node.Nodes...)
}
}
}
func hasAndroidId(n Node)bool{
return strings.Compare(n.Id,"")!=0
}
func PrintInitAndroidParam(n Node,option interface{}){
android_id := strings.Replace(n.Id,"@+id/","",-1)
str_format := "%s = (%s)%sfindViewById(R.id.%s);"
fmt.Println(fmt.Sprintf(str_format,android_id,n.XMLName.Local,option,android_id))
}
func PrintInitAndroidParamFromXML(file_path,init_view string){
if f,err := os.Open(file_path);err != nil{
log.Println(err)
}else{
defer f.Close()
b,_ := IoUtil.ReadAll(f)
var n Node
xml.Unmarshal(b,&n)
walk(n,hasAndroidId,PrintInitAndroidParam,init_view)
}
}
func PrintAndroidParam(n Node,-1)
str_format := "%s %s;"
fmt.Println(fmt.Sprintf(str_format,android_id))
}
func PrintAndroidParamFromXML(file_path string){
if f,PrintAndroidParam,nil)
}
}
func PrintAndroidParamOnClick(n Node,-1)
str_format := "%s.setOnClickListener(%s);"
fmt.Println(fmt.Sprintf(str_format,option))
}
func PrintAndroidParamOnClickFromXML(file_path string,data string){
if f,PrintAndroidParamOnClick,data)
}
}
func main() {
file_path := `/Users/zhangmike/Documents/gopath/src/git.oschina.net/zdglf/geowebsite/android/GeoApp/app/src/main/res/layout/fragment_user_info.xml`
init_view := "v."
listener_interface := "this"
PrintAndroidParamFromXML(file_path)
fmt.Println()
PrintInitAndroidParamFromXML(file_path,init_view)
fmt.Println()
PrintAndroidParamOnClickFromXML(file_path,listener_interface)
fmt.Println()
}