当前位置: 首页>>代码示例>>Golang>>正文


Golang xml.MarshalIndent函数代码示例

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


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

示例1: TestOutAndBackIn

func TestOutAndBackIn(t *testing.T) {

	const ID = "/test1"

	ref := newRoute(ID)

	x, err := xml.MarshalIndent(ref, "", "  ")
	if err != nil {
		t.Error(err)
	}

	/*t.Log("ref as xml is :", string(x))*/

	var fresh Route //only empty fields

	err = xml.Unmarshal(x, &fresh)
	if err != nil {
		t.Error(err)
	}

	var x2 []byte
	x2, err = xml.MarshalIndent(fresh, "", "  ")
	if err != nil {
		t.Error(err)
	}

	t.Log("fresh as xml is:", string(x2))

	if string(x) != string(x2) {
		t.Error("not equal, sorry MAC")
	}

}
开发者ID:docstream,项目名称:model-go,代码行数:33,代码来源:dbobjects_test.go

示例2: MakeRequest

func (c *Client) MakeRequest(otype, result string, updateCheck, isPing bool) (*omaha.Response, error) {
	client := &http.Client{}
	req := c.OmahaRequest(otype, result, updateCheck, isPing)
	raw, err := xml.MarshalIndent(req, "", " ")
	if err != nil {
		return nil, err
	}

	resp, err := client.Post(c.config.server+"/v1/update/", "text/xml", bytes.NewReader(raw))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	oresp := new(omaha.Response)
	err = xml.NewDecoder(resp.Body).Decode(oresp)
	if err != nil {
		return nil, err
	}

	if instanceFlags.verbose {
		raw, _ := xml.MarshalIndent(req, "", " ")
		c.Log("request: %s\n", string(raw))
		raw, _ = xml.MarshalIndent(oresp, "", " ")
		c.Log("response: %s\n", string(raw))
	}

	return oresp, nil
}
开发者ID:stuart-warren,项目名称:updateservicectl,代码行数:29,代码来源:instance.go

示例3: processAtom

func (cs *contentStore) processAtom(rawContent []byte, topic Topic) {
	atomFeed := &feeds.AtomFeed{}
	err := xml.Unmarshal(rawContent, atomFeed)
	if err != nil {
		log.Println("Couldn't parse atom content", err.Error())
		return
	}

	items := cs.content[topic]
	if items == nil {
		cs.content[topic] = make(map[time.Time]string)
		items = cs.content[topic]
	}

	sortedDates := cs.contentSortedItems[topic]
	if sortedDates == nil {
		cs.contentSortedItems[topic] = make([]time.Time, 0, len(atomFeed.Entries))
		sortedDates = cs.contentSortedItems[topic]
	}

	for _, newItem := range atomFeed.Entries {
		date, err := time.Parse(time.RFC3339, newItem.Updated)
		if err != nil {
			log.Printf("Couldn't parse %s as a RFC3339 date. Not accepting this.", newItem.Updated)
			continue
		}

		content, err := xml.MarshalIndent(newItem, "", "  ")
		if err != nil {
			log.Println("Couldn't re-marshal element:", err.Error())
			continue
		}

		sortedDates = insertDate(sortedDates, date)
		items[date] = string(content)
	}

	cs.contentSortedItems[topic] = sortedDates

	// since no one is supposed to use it afterwards ...
	atomFeed.Entries = []*feeds.AtomEntry{}
	header, err := xml.MarshalIndent(atomFeed, "", "  ")
	if err != nil {
		log.Println("Error when re-marshaling header:", err.Error())
	}

	cs.contentHeader[topic] = string(header)
}
开发者ID:rakoo,项目名称:psgb,代码行数:48,代码来源:contentstore.go

示例4: openStreamAndGetFeatures

func (c *Client) openStreamAndGetFeatures() (*streamFeatures, error) {
	// Declare intent to be a xmpp client.
	openStream := fmt.Sprintf("<?xml version='1.0'?><stream:stream to='%s' xmlns='%s' xmlns:stream='%s' version='1.0'>",
		xmlEscape(c.domain), nsClient, nsStream)
	if Debug {
		fmt.Printf("===xmpp===send:\n%s\n", openStream)
	}
	fmt.Fprint(c.conn, openStream)

	// Server should respond with a stream opening.
	se, err := nextStart(c.p)
	if err != nil {
		return nil, err
	}

	if se.Name.Space != nsStream || se.Name.Local != "stream" {
		return nil, errors.New("xmpp: expected <stream> but got <" + se.Name.Local + "> in " + se.Name.Space)
	}

	features := &streamFeatures{}
	if err = c.p.DecodeElement(features, nil); err != nil {
		return nil, errors.New("unmarshal <features>: " + err.Error())
	}
	if Debug {
		bytes, err := xml.MarshalIndent(features, "", "    ")
		if err == nil {
			fmt.Printf("===xmpp===receive:%s\n", string(bytes))
		}
	}
	return features, nil
}
开发者ID:NoahShen,项目名称:go-xmpp,代码行数:31,代码来源:xmpp.go

示例5: WriteAsXml

// WriteAsXml is a convenience method for writing a value in xml (requires Xml tags on the value)
func (r *Response) WriteAsXml(value interface{}) error {
	var output []byte
	var err error

	if value == nil { // do not write a nil representation
		return nil
	}
	if r.prettyPrint {
		output, err = xml.MarshalIndent(value, " ", " ")
	} else {
		output, err = xml.Marshal(value)
	}

	if err != nil {
		return r.WriteError(http.StatusInternalServerError, err)
	}
	r.Header().Set(HEADER_ContentType, MIME_XML)
	if r.statusCode > 0 { // a WriteHeader was intercepted
		r.ResponseWriter.WriteHeader(r.statusCode)
	}
	_, err = r.Write([]byte(xml.Header))
	if err != nil {
		return err
	}
	if _, err = r.Write(output); err != nil {
		return err
	}
	return nil
}
开发者ID:shenjinxi,项目名称:go-restful,代码行数:30,代码来源:response.go

示例6: XML

func (req DatasourceCreateRequest) XML() ([]byte, error) {
	tmp := struct {
		DatasourceCreateRequest
		XMLName struct{} `xml:"tsRequest"`
	}{DatasourceCreateRequest: req}
	return xml.MarshalIndent(tmp, "", "   ")
}
开发者ID:mattbaird,项目名称:tableau4go,代码行数:7,代码来源:model.go

示例7: Convert

func (b *blankTarget) Convert(w io.Writer) error {

	var doc, err = xliffFromFile(b.inFile)
	if err != nil {
		return err
	}

	for i := range doc.File {
		doc.File[i].TargetLang = ""
		for j := range doc.File[i].Body.TransUnit {
			doc.File[i].Body.TransUnit[j].Target.Lang = ""
			doc.File[i].Body.TransUnit[j].Target.Inner = ""
		}
	}

	var out []byte
	if out, err = xml.MarshalIndent(doc, "", "  "); err != nil {
		return err
	}

	io.WriteString(w, xml.Header)
	w.Write(out)

	return nil
}
开发者ID:travelping,项目名称:xliffer,代码行数:25,代码来源:blank_target.go

示例8: createView

func createView(results []AvailabilityProfileOutput) ([]byte, error) {

	docRoot := &ReadRoot{}
	for _, row := range results {
		profile := &Profile{
			ID:        row.ID.Hex(),
			Name:      row.Name,
			Namespace: row.Namespace,
			Poem:      row.Poems[0],
		}
		and := &And{}
		docRoot.Profile = append(docRoot.Profile, profile)
		for _, group := range row.Groups {
			or := &Or{}
			for _, sf := range group {
				group := &Group{
					ServiceFlavor: sf,
				}
				or.Group = append(or.Group, group)
			}
			and.Or = append(and.Or, or)
		}
		profile.And = and
	}
	output, err := xml.MarshalIndent(docRoot, " ", "  ")
	return output, err

}
开发者ID:ntrianta,项目名称:ar-web-api,代码行数:28,代码来源:availabilityProfilesView.go

示例9: MarshalXmlToData

func MarshalXmlToData(object interface{}) ([]byte, error) {
	if data, err := xml.MarshalIndent(object, "", "    "); err != nil {
		return nil, err
	} else {
		return data, nil
	}
}
开发者ID:shiwei0124,项目名称:gobase,代码行数:7,代码来源:xml_parser.go

示例10: Exec

func (*RssPlugin) Exec(topCtx mustache.Context) {
	title := FromCtx(topCtx, "site.title").(string)
	production_url := FromCtx(topCtx, "site.config.production_url").(string)
	pubDate := time.Now().Format("2006-01-02 03:04:05 +0800")
	post_ids := FromCtx(topCtx, "db.posts.chronological").([]string)
	posts := FromCtx(topCtx, "db.posts.dictionary").(map[string]Mapper)
	items := make([]RssItem, 0)
	for _, id := range post_ids {
		post := posts[id]
		item := RssItem{post.GetString("title"), production_url + post.Url(), post["_date"].(time.Time).Format("2006-01-02 03:04:05 +0800"), post["_content"].(*DocContent).Main}
		items = append(items, item)
	}
	rss := &Rss{"2.0", &RssChannel{title, production_url, pubDate, items}}
	f, err := os.OpenFile("compiled/rss.xml", os.O_CREATE|os.O_WRONLY, os.ModePerm)
	if err != nil {
		log.Println("ERR When Create RSS", err)
		return
	}
	defer f.Close()
	data, err := xml.MarshalIndent(rss, "", "  ")
	if err != nil {
		log.Println("ERR When Create RSS", err)
		return
	}
	f.WriteString(`<?xml version="1.0"?>` + "\n" + `<rss version="2.0">`)
	f.Write(data[len(`<rss version="2.0">`)+1 : len(data)-len("</Rss>")])
	f.WriteString("</rss>")
	f.Sync()
	return
}
开发者ID:xushiwei,项目名称:gor,代码行数:30,代码来源:plugins.go

示例11: Get

func (s *ReportDownloadService) Get(reportDefinition ReportDefinition) (res interface{}, err error) {
	reportDefinition.Selector.XMLName = xml.Name{baseUrl, "selector"}
	repDef := reportDefinitionXml{
		ReportDefinition: &reportDefinition,
		XMLName: xml.Name{
			Space: baseUrl,
			Local: "reportDefinition",
		},
	}
	body, err := xml.MarshalIndent(repDef, "  ", "  ")
	if err != nil {
		return res, err
	}
	form := url.Values{}
	form.Add("__rdxml", string(body))
	resp, err := s.makeRequest(form)
	if err != nil {
		return res, err
	}
	/*respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return res, err
	}
	return string(respBody), err*/
	return parseReport(resp.Body)
}
开发者ID:rfink,项目名称:gads,代码行数:26,代码来源:report_download.go

示例12: Test_AddAzureVMExtensionConfiguration

func Test_AddAzureVMExtensionConfiguration(t *testing.T) {

	role := vm.Role{}
	AddAzureVMExtensionConfiguration(&role,
		"nameOfExtension", "nameOfPublisher", "versionOfExtension", "nameOfReference", "state", []byte{1, 2, 3}, []byte{})

	data, err := xml.MarshalIndent(role, "", "  ")
	if err != nil {
		t.Fatal(err)
	}
	if expected := `<Role>
  <ConfigurationSets></ConfigurationSets>
  <ResourceExtensionReferences>
    <ResourceExtensionReference>
      <ReferenceName>nameOfReference</ReferenceName>
      <Publisher>nameOfPublisher</Publisher>
      <Name>nameOfExtension</Name>
      <Version>versionOfExtension</Version>
      <ResourceExtensionParameterValues>
        <ResourceExtensionParameterValue>
          <Key>ignored</Key>
          <Value>AQID</Value>
          <Type>Public</Type>
        </ResourceExtensionParameterValue>
      </ResourceExtensionParameterValues>
      <State>state</State>
    </ResourceExtensionReference>
  </ResourceExtensionReferences>
  <DataVirtualHardDisks></DataVirtualHardDisks>
</Role>`; string(data) != expected {
		t.Fatalf("Expected %q, but got %q", expected, string(data))
	}
}
开发者ID:garimakhulbe,项目名称:azure-sdk-for-go,代码行数:33,代码来源:extensions_test.go

示例13: CreateXML

//CreateXML encode into xml
func (msg *GetParameterValuesResponse) CreateXML() []byte {
	env := Envelope{}
	id := IDStruct{"1", msg.GetID()}
	env.XmlnsEnv = "http://schemas.xmlsoap.org/soap/envelope/"
	env.XmlnsEnc = "http://schemas.xmlsoap.org/soap/encoding/"
	env.XmlnsXsd = "http://www.w3.org/2001/XMLSchema"
	env.XmlnsXsi = "http://www.w3.org/2001/XMLSchema-instance"
	env.XmlnsCwmp = "urn:dslforum-org:cwmp-1-0"
	env.Header = HeaderStruct{ID: id}

	paramLen := strconv.Itoa(len(msg.Values))
	params := ParameterListStruct{Type: "cwmp:ParameterValueStruct[" + paramLen + "]"}
	for k, v := range msg.Values {
		param := ParameterValueStruct{
			Name:  NodeStruct{Type: XsdString, Value: k},
			Value: NodeStruct{Type: XsdString, Value: v}}
		params.Params = append(params.Params, param)
	}
	info := getParameterValuesResponseStruct{Params: params}
	env.Body = getParameterValuesResponseBodyStruct{info}
	output, err := xml.MarshalIndent(env, "  ", "    ")
	//output, err := xml.Marshal(env)
	if err != nil {
		fmt.Printf("error: %v\n", err)
	}
	return output
}
开发者ID:it-man-cn,项目名称:go-acs,代码行数:28,代码来源:GetParameterValuesResponse.go

示例14: XMLIndent

// XMLIndent sends an XML response with status code, but it applies prefix and indent to format the output.
func (p Print) XMLIndent(code int, i interface{}, prefix string, indent string) (err error) {
	b, err := xml.MarshalIndent(i, prefix, indent)
	if err != nil {
		return err
	}
	return p.xml(code, b)
}
开发者ID:joao-parana,项目名称:csfw,代码行数:8,代码来源:response.go

示例15: Marshal

func (stx3 *Stx3) Marshal() ([]byte, error) {
	result, err := xml.MarshalIndent(stx3, "  ", "    ")

	fullXml := xml.Header + string(result)

	return []byte(fullXml), err
}
开发者ID:seasonlabs,项目名称:as24go,代码行数:7,代码来源:stx3.go


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