本文整理汇总了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")
}
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例6: XML
func (req DatasourceCreateRequest) XML() ([]byte, error) {
tmp := struct {
DatasourceCreateRequest
XMLName struct{} `xml:"tsRequest"`
}{DatasourceCreateRequest: req}
return xml.MarshalIndent(tmp, "", " ")
}
示例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
}
示例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
}
示例9: MarshalXmlToData
func MarshalXmlToData(object interface{}) ([]byte, error) {
if data, err := xml.MarshalIndent(object, "", " "); err != nil {
return nil, err
} else {
return data, nil
}
}
示例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
}
示例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)
}
示例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))
}
}
示例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
}
示例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)
}
示例15: Marshal
func (stx3 *Stx3) Marshal() ([]byte, error) {
result, err := xml.MarshalIndent(stx3, " ", " ")
fullXml := xml.Header + string(result)
return []byte(fullXml), err
}