• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang xml.Unmarshal函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中encoding/xml.Unmarshal函数的典型用法代码示例。如果您正苦于以下问题:Golang Unmarshal函数的具体用法?Golang Unmarshal怎么用?Golang Unmarshal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Unmarshal函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: DecodeClientToClientMessage

func DecodeClientToClientMessage(msg []byte) (Type, *UserToUserPackage, error) {
	var m ClientToClientMessage
	err := xml.Unmarshal(msg, &m)
	if err != nil {
		return UNKNOWN_T, nil, err
	}
	switch m.Type {
	case VOTE:
		var v VoteMessage
		err := xml.Unmarshal(msg, &v)
		if err != nil {
			return UNKNOWN_T, nil, errors.New("Couldn't decode the message: Broadcast or direct message malformed")
		}
		uu := UserToUserPackage{
			VoteMessage: &v,
		}
		return VOTE_T, &uu, nil
	case COORDINATOR:
		var v CoordinatorMessage
		err := xml.Unmarshal(msg, &v)
		if err != nil {
			return UNKNOWN_T, nil, errors.New("Couldn't decode the message: Broadcast or direct message malformed")
		}
		uu := UserToUserPackage{
			CoordinatorMessage: &v,
		}
		return COORDINATOR_T, &uu, nil
	}
	return UNKNOWN_T, nil, errors.New("Couldn't decode the message: No matching type")
}
开发者ID:Madrigal,项目名称:GoUDP,代码行数:30,代码来源:message.go


示例2: RegisterDevice

func RegisterDevice(token string, customData string, userId string,
	userSecret string, region string, applicationArn string) (arn string, err error) {
	values := url.Values{}
	values.Set("Action", "CreatePlatformEndpoint")
	values.Set("CustomUserData", customData)
	values.Set("Token", token)
	values.Set("PlatformApplicationArn", applicationArn)
	values.Set("Timestamp", time.Now().UTC().Format(time.RFC3339))

	response, err := makeRequest("http://sns."+region+".amazonaws.com/",
		values, userId, userSecret, region)

	if err != nil {
		return "", err
	}

	defer response.Body.Close()

	if response.StatusCode != 200 {
		content, _ := ioutil.ReadAll(response.Body)
		var errorResponse aws.ErrorResponse
		xml.Unmarshal(content, &errorResponse)
		return "", errors.New("Unable to register device. " + errorResponse.Error.Code + ": " + errorResponse.Error.Message)
	} else {
		content, _ := ioutil.ReadAll(response.Body)
		var createResponse CreateResponse
		xml.Unmarshal(content, &createResponse)
		return createResponse.CreatePlatformEndpointResult.EndpointArn, nil
	}
}
开发者ID:usmanismail,项目名称:gpns,代码行数:30,代码来源:snsclient.go


示例3: loadCloudFormationResource

func (client *Client) loadCloudFormationResource(action string, params Values, i interface{}) error {
	req, e := client.signedCloudFormationRequest(action, params)

	rsp, e := httpClient.Do(req)
	if e != nil {
		return e
	}
	defer rsp.Body.Close()
	b, e := ioutil.ReadAll(rsp.Body)
	if e != nil {
		return e
	}
	switch rsp.StatusCode {
	case 404:
		return ErrorNotFound
	case 200:
		if i != nil {
			return xml.Unmarshal(b, i)
		}
		return nil
	default:
		ersp := &ErrorResponse{}
		dbg.Printf("ERROR=%q", string(b))
		e = xml.Unmarshal(b, ersp)
		if e != nil {
			return fmt.Errorf("expected status 2xx but got %s (%s)", rsp.Status, string(b))

		}
		if strings.Contains(ersp.Error.Message, "does not exist") {
			return ErrorNotFound
		}
		return fmt.Errorf(ersp.Error.Message)
	}
}
开发者ID:himanshugpt,项目名称:evergreen,代码行数:34,代码来源:main.go


示例4: Analyse

//解析配置文件内容至内存中
func Analyse() error {

	content, err := ioutil.ReadFile("../etc/config.xml")

	if err != nil {
		Log.Error(err)
		return err
	}

	err = xml.Unmarshal(content, &config)
	if err != nil {
		Log.Error(err)
		return err
	}

	content, err = ioutil.ReadFile("../etc/entity.xml")
	err = xml.Unmarshal(content, &entitys)

	if err != nil {
		Log.Error(err)
		return err
	}

	content, err = ioutil.ReadFile("../etc/url.xml")
	err = xml.Unmarshal(content, &urls)

	if err != nil {
		Log.Error(err)
		return err
	}

	return nil
}
开发者ID:huangjq,项目名称:lessgo,代码行数:34,代码来源:lessgo.go


示例5: WexinHandler

func WexinHandler(resp http.ResponseWriter, req *http.Request) {

	log.Println("method:", req.Method)
	if req.Method == "GET" {
		weixinValid(resp, req)
	} else {

		data, err := ioutil.ReadAll(req.Body)
		if nil != err {
			log.Println("read body err:", err)
			return
		}
		log.Println("data:", string(data))

		request := &entry.ReqMessage{}
		er := xml.Unmarshal(data, request)
		if nil != er {
			log.Println("decode body err:", er)
			return
		}

		event := request.Event
		msgType := request.MsgType
		ch := make(chan interface{})
		defer close(ch)
		if "event" == msgType && event == "subscribe" {
			//添加关注事件
			go subEventProcess(*request, ch)

		} else if "event" == msgType && event == "unsubscribe" {
			//取消订阅
			go unsubEventProcess(*request, ch)

		} else if "location" == msgType {
			//地理位置
			var msg entry.LocRequest
			err := xml.Unmarshal(data, &msg)
			if nil != err {
				log.Println("decode txt request body err:", err)
				return
			}

			go locMessageProcess(msg, ch)

		} else {
			var msg entry.TxtRequest
			err := xml.Unmarshal(data, &msg)
			if nil != err {
				log.Println("decode txt request body err:", er)
				return
			}

			go txtMessageProcess(msg, ch)
		}

		brespons, _ := xml.Marshal(<-ch)
		log.Println(string(brespons))
		resp.Write(brespons)
	}
}
开发者ID:houzhenggang,项目名称:weixin-1,代码行数:60,代码来源:weixin.go


示例6: GetLocationOfBucket

func (c *AliOSSClient) GetLocationOfBucket(bucket string) (string, error) {
	uri := fmt.Sprintf("/%s/?location", bucket)
	query := make(map[string]string)
	query["location"] = ""
	s := &oss_agent{
		AccessKey:            c.AccessKey,
		AccessKeySecret:      c.AccessKeySecret,
		Verb:                 "GET",
		Url:                  fmt.Sprintf("http://%s.%s", bucket, c.EndPoint),
		CanonicalizedHeaders: make(map[string]string),
		CanonicalizedUri:     uri,
		CanonicalizedQuery:   query,
		Content:              &bytes.Reader{},
		ContentType:          "",
		Debug:                c.Debug,
		logger:               c.logger,
	}

	v := ""
	e := &AliOssError{}
	resp, xml_result, err := s.send_request(false)
	if err != nil {
		return "", err
	}
	if resp.StatusCode == 200 {
		xml.Unmarshal(xml_result, &v)
		return v, nil
	} else {
		xml.Unmarshal(xml_result, e)
		return "", e
	}
}
开发者ID:sundq,项目名称:gooss,代码行数:32,代码来源:bucket.go


示例7: callRet

func callRet(ret interface{}, resp *http.Response) (code int, err error) {
	var (
		b  []byte
		er errRet
	)
	code = resp.StatusCode
	if code/100 == 2 {
		if ret == nil || resp.ContentLength == 0 {
			return
		}
		b, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			return
		}
		ct := resp.Header.Get("Content-Type")
		if strings.Contains(ct, "application/json") {
			err = json.Unmarshal(b, ret)
		} else { // default decoding
			err = xml.Unmarshal(b, ret)
		}
	} else {
		if resp.ContentLength == 0 {
			return
		}
		b, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			return
		}
		if err = xml.Unmarshal(b, &er); err != nil {
			return
		}
		err = errors.New(er.Code)
	}
	return
}
开发者ID:nowa,项目名称:OCSS,代码行数:35,代码来源:rpc.go


示例8: main

func main() {
	data, err := ioutil.ReadFile("page.xml")
	if nil != err {
		fmt.Println(err)
	}
	{
		v := new(BlogContainer)
		err = xml.Unmarshal(data, v)
		if nil != err {
			fmt.Println(err)
			return
		}

		fmt.Printf("XMLName: %#v\n", v.XMLName)
		fmt.Printf("XMLName: %#v\n", v.Chapter.XMLName)
		fmt.Printf("Title: %v\n", v.Chapter.Title)
		for i, x := range v.Chapter.Name {
			fmt.Printf("Chapter %d: %v\n", i, x)
		}
	}
	{
		v := new(Blog)
		err = xml.Unmarshal(data, v)
		if nil != err {
			fmt.Println(err)
			return
		}
		fmt.Println(v.Title)
		fmt.Println(v.Tags)
		fmt.Println(v.Chapters)
	}
}
开发者ID:henglinli,项目名称:goblog,代码行数:32,代码来源:xml.go


示例9: cachingReadEntity

func (r *Request) cachingReadEntity(contentType string, entityPointer interface{}) (err error) {
	var buffer []byte
	if r.bodyContent != nil {
		buffer = *r.bodyContent
	} else {
		buffer, err = ioutil.ReadAll(r.Request.Body)
		if err != nil {
			return err
		}
		r.bodyContent = &buffer
	}
	if strings.Contains(contentType, MIME_XML) {
		return xml.Unmarshal(buffer, entityPointer)
	}
	if strings.Contains(contentType, MIME_JSON) {
		return json.Unmarshal(buffer, entityPointer)
	}
	if MIME_XML == defaultRequestContentType {
		return xml.Unmarshal(buffer, entityPointer)
	}
	if MIME_JSON == defaultRequestContentType {
		return json.Unmarshal(buffer, entityPointer)
	}
	return NewError(400, "Unable to unmarshal content of type:"+contentType)
}
开发者ID:gtarcea,项目名称:1DevDayTalk2014,代码行数:25,代码来源:request.go


示例10: ReadCommandsFile

func ReadCommandsFile(basedir string) (*CommandsXML, error) {
	commandsdata, err := ioutil.ReadFile(filepath.Join(basedir, "doc", "commands-xml", "commands.xml"))
	if err != nil {
		return nil, err
	}
	cs := &CommandsXMLSimple{}
	err = xml.Unmarshal(commandsdata, cs)
	if err != nil {
		return nil, err
	}

	c := &CommandsXML{}
	c.de = make(map[string]CommandsxmlCommand)
	c.en = make(map[string]CommandsxmlCommand)
	commandTranslationsEnDe = make(map[string]string)

	for _, v := range cs.Commands {
		commandTranslationsEnDe[v.En] = v.De
	}
	err = xml.Unmarshal(commandsdata, c)
	if err != nil {
		return nil, err
	}
	for _, v := range c.Commands {
		c.de[v.De] = v
		c.en[v.En] = v
	}
	return c, err
}
开发者ID:speedata,项目名称:publisher,代码行数:29,代码来源:commandsxml.go


示例11: ParseFileList

func ParseFileList(in io.Reader, out *FileListing) (err error) {
	defer func() { out.Name = out.Base }()
	data, err := ioutil.ReadAll(in)
	if err != nil {
		return
	}

	/* First, try just reading it */
	err = xml.Unmarshal(data, out)
	if err == nil {
		return
	}

	/* If that failed, then try to read in another charset. This happens because
	 * microdc2 is known to lie by saying that the content is utf-8 when it's
	 * actually iso-8859-1 */
	translator, err := charset.TranslatorFrom("iso-8859-1")
	if err != nil {
		return
	}
	_, data, err = translator.Translate(data, true)
	if err != nil {
		return
	}
	return xml.Unmarshal(data, out)
}
开发者ID:alexcrichton,项目名称:fargo,代码行数:26,代码来源:list.go


示例12: GetCoreRule

//get cores rule
func (c *AliOSSClient) GetCoreRule(bucket string) (*CORSConfiguration, error) {
	uri := fmt.Sprintf("/%s/?cors", bucket)
	query := make(map[string]string)
	header := make(map[string]string)
	query["cors"] = ""
	s := &oss_agent{
		AccessKey:            c.AccessKey,
		AccessKeySecret:      c.AccessKeySecret,
		Verb:                 "GET",
		Url:                  fmt.Sprintf("http://%s.%s", bucket, c.EndPoint),
		CanonicalizedHeaders: header,
		CanonicalizedUri:     uri,
		CanonicalizedQuery:   query,
		Content:              &bytes.Reader{},
		Debug:                c.Debug,
		logger:               c.logger,
	}

	v := &CORSConfiguration{}
	e := &AliOssError{}
	resp, xml_result, err := s.send_request(false)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode/100 == 2 {
		xml.Unmarshal(xml_result, v)
		return v, nil
	} else {
		xml.Unmarshal(xml_result, e)
		return nil, e
	}
}
开发者ID:sundq,项目名称:gooss,代码行数:33,代码来源:object.go


示例13: GetInitMultipartUpload

//Init multipart upload
func (c *AliOSSClient) GetInitMultipartUpload(bucket string, key string) (*MultiUploadInit, error) {
	uri := fmt.Sprintf("/%s/%s?uploads", bucket, key)
	query := make(map[string]string)
	header := make(map[string]string)
	query["uploads"] = ""
	s := &oss_agent{
		AccessKey:            c.AccessKey,
		AccessKeySecret:      c.AccessKeySecret,
		Verb:                 "POST",
		Url:                  fmt.Sprintf("http://%s.%s/%s", bucket, c.EndPoint, key),
		CanonicalizedHeaders: header,
		CanonicalizedUri:     uri,
		CanonicalizedQuery:   query,
		Content:              &bytes.Reader{},
		Debug:                c.Debug,
		logger:               c.logger,
	}

	v := &MultiUploadInit{}
	e := &AliOssError{}
	resp, xml_result, err := s.send_request(false)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode/100 == 2 {
		xml.Unmarshal(xml_result, v)
		return v, nil
	} else {
		xml.Unmarshal(xml_result, e)
		return nil, e
	}
}
开发者ID:sundq,项目名称:gooss,代码行数:33,代码来源:object.go


示例14: main

func main() {
	f, err := ioutil.ReadFile("example.xml")
	check(err)

	a := new(lib.Spells)

	err = xml.Unmarshal(f, &a)
	check(err)
	fmt.Printf("%+v", a)
	fmt.Println(" ")

	result, err := json.MarshalIndent(a, "", "  ")
	check(err)
	fmt.Printf("%+v", string(result))

	data := []byte("<cells><cell><name>Thomas</name></cell><cell><name>Janes</name></cell></cells>")

	b := new(Cells)

	err = xml.Unmarshal(data, &b)
	check(err)
	fmt.Printf("%+v", b)

	dataJson, err := json.MarshalIndent(b, "", "  ")
	check(err)
	fmt.Println(string(dataJson))

	c := new(TmpJson)

	err = json.Unmarshal(dataJson, &c)
	check(err)
	fmt.Printf("\n\n%+v", c)

}
开发者ID:jrmiller82,项目名称:gmaster-helper,代码行数:34,代码来源:scratch-xml.go


示例15: CloseBucketLogging

func (c *AliOSSClient) CloseBucketLogging(name string) error {
	xml_content := `<?xml version="1.0" encoding="UTF-8"?><BucketLoggingStatus></BucketLoggingStatus>`
	uri := fmt.Sprintf("/%s/?logging", name)
	query := make(map[string]string)
	header := make(map[string]string)
	query["logging"] = ""

	s := &oss_agent{
		AccessKey:            c.AccessKey,
		AccessKeySecret:      c.AccessKeySecret,
		Verb:                 "PUT",
		Url:                  fmt.Sprintf("http://%s.%s", name, c.EndPoint),
		CanonicalizedHeaders: header,
		CanonicalizedUri:     uri,
		CanonicalizedQuery:   query,
		Content:              bytes.NewReader([]byte(xml_content)),
		ContentType:          "application/xml",
		Debug:                c.Debug,
		logger:               c.logger,
	}

	v := &BucketList{}
	e := &AliOssError{}
	resp, xml_result, err := s.send_request(false)
	if err != nil {
		return err
	}
	if resp.StatusCode/100 == 2 {
		xml.Unmarshal(xml_result, v)
		return nil
	} else {
		xml.Unmarshal(xml_result, e)
		return e
	}
}
开发者ID:sundq,项目名称:gooss,代码行数:35,代码来源:bucket.go


示例16: CheckForUpdate

func (this *ZoneGroupTopology) CheckForUpdate(updateType UpdateType, cachedOnly bool, version string) (updateItem *UpdateItem, err error) {
	type UpdateItemHolder struct {
		XMLName xml.Name
		UpdateItem
	}
	type UpdateItemText struct {
		XMLName xml.Name
		Text    string `xml:",chardata"`
	}
	type Response struct {
		XMLName    xml.Name
		UpdateItem UpdateItemText
		ErrorResponse
	}
	args := []Arg{
		{"UpdateType", updateType},
		{"CachedOnly", cachedOnly},
		{"Version", version},
	}
	response := this.Svc.Call("CheckForUpdate", args)
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	rec := UpdateItemHolder{}
	xml.Unmarshal([]byte(doc.UpdateItem.Text), &rec)
	updateItem = &rec.UpdateItem
	err = doc.Error()
	return
}
开发者ID:ninjasphere,项目名称:go-sonos,代码行数:28,代码来源:ZoneGroupTopology.go


示例17: DeleteBucket

//Delete bucket
func (c *AliOSSClient) DeleteBucket(name string) error {
	uri := fmt.Sprintf("/%s/", name)
	query := make(map[string]string)
	header := make(map[string]string)

	s := &oss_agent{
		AccessKey:            c.AccessKey,
		AccessKeySecret:      c.AccessKeySecret,
		Verb:                 "DELETE",
		Url:                  fmt.Sprintf("http://%s.%s", name, c.EndPoint),
		CanonicalizedHeaders: header,
		CanonicalizedUri:     uri,
		CanonicalizedQuery:   query,
		Content:              &bytes.Reader{},
		Debug:                c.Debug,
		logger:               c.logger,
	}

	v := &BucketList{}
	e := &AliOssError{}
	resp, xml_result, err := s.send_request(false)
	if err != nil {
		return err
	}
	if resp.StatusCode/100 == 2 {
		xml.Unmarshal(xml_result, v)
		return nil
	} else {
		xml.Unmarshal(xml_result, e)
		return e
	}
}
开发者ID:sundq,项目名称:gooss,代码行数:33,代码来源:bucket.go


示例18: Browse

func (this *ContentDirectory) Browse(req *BrowseRequest) (browseResult *BrowseResult, err error) {
	type Response struct {
		XMLName xml.Name
		Result  string
		BrowseResult
		upnpErrorResponse
	}
	args := []upnpArg{
		{"ObjectID", req.ObjectID},
		{"BrowseFlag", req.BrowseFlag},
		{"Filter", req.Filter},
		{"StartingIndex", req.StartingIndex},
		{"RequestedCount", req.RequestCount},
		{"SortCriteria", req.SortCriteria},
	}
	response := this.Svc.Call("Browse", args)
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	doc.Doc = &didl.Lite{}
	// log.Printf("%s", doc.Result)
	xml.Unmarshal([]byte(doc.Result), doc.Doc)
	browseResult = &doc.BrowseResult
	err = doc.Error()
	return
}
开发者ID:adamreeve,项目名称:go-sonos,代码行数:25,代码来源:ContentDirectory.go


示例19: GetBucketWebsite

func (c *AliOSSClient) GetBucketWebsite(name string) (*BucketWebsite, error) {
	uri := fmt.Sprintf("/%s/?website", name)
	query := make(map[string]string)
	header := make(map[string]string)
	query["website"] = ""

	s := &oss_agent{
		AccessKey:            c.AccessKey,
		AccessKeySecret:      c.AccessKeySecret,
		Verb:                 "GET",
		Url:                  fmt.Sprintf("http://%s.%s", name, c.EndPoint),
		CanonicalizedHeaders: header,
		CanonicalizedUri:     uri,
		CanonicalizedQuery:   query,
		Content:              &bytes.Reader{},
		ContentType:          "application/xml",
		Debug:                c.Debug,
		logger:               c.logger,
	}

	v := &BucketWebsite{}
	e := &AliOssError{}
	resp, xml_result, err := s.send_request(false)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode/100 == 2 {
		xml.Unmarshal(xml_result, v)
		return v, nil
	} else {
		xml.Unmarshal(xml_result, e)
		return nil, e
	}
}
开发者ID:sundq,项目名称:gooss,代码行数:34,代码来源:bucket.go


示例20: ReadEntity

// ReadEntity checks the Accept header and reads the content into the entityPointer
// May be called multiple times in the request-response flow
func (r *Request) ReadEntity(entityPointer interface{}) (err error) {
	contentType := r.Request.Header.Get(HEADER_ContentType)

	var buffer []byte
	if r.bodyContent != nil {
		buffer = *r.bodyContent
	} else {
		buffer, err = ioutil.ReadAll(r.Request.Body)
		r.bodyContent = &buffer
		if err != nil {
			return err
		}
	}
	if strings.Contains(contentType, MIME_XML) {
		return xml.Unmarshal(buffer, entityPointer)
	}
	if strings.Contains(contentType, MIME_JSON) {
		return json.Unmarshal(buffer, entityPointer)
	}
	if MIME_XML == defaultRequestContentType {
		return xml.Unmarshal(buffer, entityPointer)
	}
	if MIME_JSON == defaultRequestContentType {
		return json.Unmarshal(buffer, entityPointer)
	}
	return errors.New("[restful] Unable to unmarshal content of type:" + contentType)
}
开发者ID:sguzwf,项目名称:mertiwiki,代码行数:29,代码来源:request.go



注:本文中的encoding/xml.Unmarshal函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang xml.Decoder类代码示例发布时间:2022-05-24
下一篇:
Golang xml.NewEncoder函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap