package main import ( "github.com/tidwall/gjson" "fmt" "github.com/beevik/etree" "os" ) const bottleJson = ` { "baseResponse": { "ret": 0, "errMsg": {} }, "bottleType": 0, "msgType": 1, "bottleInfo": "7s/00Uth+Isrrp2MgTIWi07eUD6jfkN0@bottle:7s/00Uth+IrIfAP6deMtsXXvAAItluU7R0LkGFw1jn0sPCTdIwzOmWWOu+FkJF0o", "usrInfo": "\u003cuserinfo signature=\"不属于我的东西,我不要。不是真心给我的东西,我不稀罕。\" sex=\"2\" country=\"CN\" city=\"west\" province=\"Tianjin\" bigheadimgurl=\"http://wx.qlogo.cn/wxplp/ver_1/XHH8acoVbrQpzpia0pzH09ezzWZZr2UXbpsg6VDBhOE5z8YYDibjQ6EtqXysCicQIdicJYPeQIVI6awN7KzStb9NtQryFWR9ia8MxMM0g5tnqSH0/0\" smallheadimgurl=\"http://wx.qlogo.cn/wxplp/ver_1/XHH8acoVbrQpzpia0pzH09ezzWZZr2UXbpsg6VDBhOE5z8YYDibjQ6EtqXysCicQIdicJYPeQIVI6awN7KzStb9NtQryFWR9ia8MxMM0g5tnqSH0/132\" /\u003e", "nickName": "翡翠蘑菇", "unknow": 3, "throwCount": 20, "fishCount": 18, "distance": 326 } ` const bottleXml = ` <userinfo signature="不属于我的东西,我不要。不是真心给我的东西,我不稀罕。" sex="2" country="CN" city="west" province="Tianjin" bigheadimgurl="http://wx.qlogo.cn/wxplp/ver_1/XHH8acoVbrQpzpia0pzH09ezzWZZr2UXbpsg6VDBhOE5z8YYDibjQ6EtqXysCicQIdicJYPeQIVI6awN7KzStb9NtQryFWR9ia8MxMM0g5tnqSH0/0" smallheadimgurl="http://wx.qlogo.cn/wxplp/ver_1/XHH8acoVbrQpzpia0pzH09ezzWZZr2UXbpsg6VDBhOE5z8YYDibjQ6EtqXysCicQIdicJYPeQIVI6awN7KzStb9NtQryFWR9ia8MxMM0g5tnqSH0/132"/> ` func parseJson(content string) { baseResponse := gjson.Get(content, "baseResponse") bottleInfo := gjson.Get(content, "bottleInfo") usrInfo := gjson.Get(content, "usrInfo") if baseResponse.Exists() { ret := baseResponse.Get("ret").Int() errMsg := baseResponse.Get("errMsg").String() fmt.Println(ret, errMsg) } if bottleInfo.Exists() { fmt.Println(bottleInfo) } if usrInfo.Exists() { fmt.Println(usrInfo) } } func parseXML(context string) { doc := etree.NewDocument() if err := doc.ReadFromString(context); err != nil { panic(err) } root := doc.SelectElement("userinfo") if root != nil { fmt.Println("Root element:", root.Tag) for _, attr := range root.Attr { fmt.Printf(" Attr: %s=%s\n", attr.Key, attr.Value) } } } func buildXML() { doc := etree.NewDocument() doc.CreateProcInst("xml", `version="1.0" encoding="UTF-8"`) doc.CreateProcInst("xml-stylesheet", `type="text/xsl" href="style.xsl"`) people := doc.CreateElement("People") people.CreateComment("These are all known people") jon := people.CreateElement("Person") jon.CreateAttr("name", "Jon") sally := people.CreateElement("Person") sally.CreateAttr("name", "Sally") doc.Indent(2) doc.WriteTo(os.Stdout) } func main() { parseJson(bottleJson) parseXML(bottleXml) buildXML() }
发表评论